Readouble

Laravel 5.3 コンソールコマンド

イントロダクションIntroduction

ArtisanはLaravelに含まれているコマンドラインインターフェイスです。アプリケーション開発全体で役に立つ、数多くのコマンドを提供しています。使用可能な全Artisanコマンドを確認するには、listコマンドを使います。Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application. To view a list of all available Artisan commands, you may use the list command:

php artisan list

全てのコマンドは「ヘルプ」が用意されており、説明と使用できる引数、オプションを表示します。ヘルプを表示するにはhelpに続いてコマンド名を入力してください。Every command also includes a "help" screen which displays and describes the command's available arguments and options. To view a help screen, simply precede the name of the command with help:

php artisan help migrate

コマンド記述Writing Commands

Artisanに用意されているコマンドに加え、独自のカスタムコマンドも構築できます。コマンドは通常、app/Console/Commandsディレクトリへ設置します。しかし、Composerによりコマンドがロードできる場所であるならば、自由に設置場所を選べます。In addition to the commands provided with Artisan, you may also build your own custom commands. Commands are typically stored in the app/Console/Commands directory; however, you are free to choose your own storage location as long as your commands can be loaded by Composer.

コマンド生成Generating Commands

新しいコマンドを作成するには、make:command Artisanコマンドを使います。このコマンドは、app/Console/Commandsディレクトリへ新しいコマンドクラスを設置します。アプリケーションにこのディレクトリがなくても心配ありません。最初に、make:command Artisanコマンドを実行するときに作成されます。生成されたコマンドには、すべてのコマンドで必要な、プロパティとメソッドがデフォルトで一揃い用意されています。To create a new command, use the make:command Artisan command. This command will create a new command class in the app/Console/Commands directory. Don't worry if this directory does not exist in your application, since it will be created the first time you run the make:command Artisan command. The generated command will include the default set of properties and methods that are present on all commands:

php artisan make:command SendEmails

Artisan CLIにより実行する前に、コマンド登録を続けて行う必要があります。Next, you will need to register the command[#registering-commands] before it can be executed via the Artisan CLI.

コマンド構造Command Structure

コマンドが生成できたら、listスクリーンでそのコマンドが表示できるように、クラスのsignaturedescriptionプロパティを指定してください。handleメソッドは、コマンド実行時に呼び出されます。コマンドのロジックは、このメソッドの中へ記述します。After generating your command, you should fill in the signature and description properties of the class, which will be used when displaying your command on the list screen. The handle method will be called when your command is executed. You may place your command logic in this method.

lightbulb">Tip!! コンソールコマンドを軽いままにし、実行内容をアプリケーションサービスとして遅らせるのは、コードの再利用性のためのグッドプラクティスです。以下の例で、メール送信の「重荷を軽く」するために、サービスクラスを注入しているところに注目してください。{tip} For greater code reuse, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks. In the example below, note that we inject a service class to do the "heavy lifting" of sending the e-mails.

コマンドのサンプルを見てみましょう。コマンドのコンストラクタで、必要な依存を注入できるところに注意を払ってください。Laravelのサービスコンテナは、コンストラクタでタイプヒントとされた依存をすべて自動的に注入します。Let's take a look at an example command. Note that we are able to inject any dependencies we need into the command's constructor. The Laravel service container[/docs/{{version}}/container] will automatically inject all dependencies type-hinted in the constructor:

<?php

namespace App\Console\Commands;

use App\User;
use App\DripEmailer;
use Illuminate\Console\Command;

class SendEmails extends Command
{
    /**
     * コンソールコマンドの名前と引数、オプション
     *
     * @var string
     */
    protected $signature = 'email:send {user}';

    /**
     * コンソールコマンドの説明
     *
     * @var string
     */
    protected $description = 'Send drip e-mails to a user';

    /**
     * drip Eメールサービス
     *
     * @var DripEmailer
     */
    protected $drip;

    /**
     * 新しいコマンドインスタンスの生成
     *
     * @param  DripEmailer  $drip
     * @return void
     */
    public function __construct(DripEmailer $drip)
    {
        parent::__construct();

        $this->drip = $drip;
    }

    /**
     * コンソールコマンドの実行
     *
     * @return mixed
     */
    public function handle()
    {
        $this->drip->send(User::find($this->argument('user')));
    }
}

クロージャコマンドClosure Commands

クロージャベースコマンドは、クラスによりコンソールコマンドを定義する方法の代替手法を提供します。ルートクロージャがコントローラの代替であるのと同じように、コマンドクロージャはコマンドクラスの代替だと考えてください。app/Console/Kernel.phpファイルのcommandsメソッドの中で、Laravelはroutes/console.phpファイルをロードしています。Closure based commands provide an alternative to defining console commands as classes. In the same way that route Closures are an alternative to controllers, think of command Closures as an alternative to command classes. Within the commands method of your app/Console/Kernel.php file, Laravel loads the routes/console.php file:

/**
 * アプリケーションのクロージャベースコマンドの登録
 *
 * @return void
 */
protected function commands()
{
    require base_path('routes/console.php');
}

このファイルがHTTPルートを定義していないとしても、アプリケーションへのコンソールベースのエントリポイント(ルート)を定義しているのです。Artisan::commandメソッドを使い、全クロージャベースルートをこのファイル中で定義します。commandメソッドはコマンドの使い方と、コマンドの引数とオプションを受け取るクロージャを引数として受け取ります。Even though this file does not define HTTP routes, it defines console based entry points (routes) into your application. Within this file, you may define all of your Closure based routes using the Artisan::command method. The command method accepts two arguments: the command signature[#defining-input-expectations] and a Closure which receives the commands arguments and options:

Artisan::command('build {project}', function ($project) {
    $this->info("Building {$project}!");
});

クロージャは裏で動作するコマンドインスタンスと結合します。そのため、完全なコマンドクラス上でアクセスできる、通常のヘルパメソッドにすべてアクセスできます。The Closure is bound to the underlying command instance, so you have full access to all of the helper methods you would typically be able to access on a full command class.

依存のタイプヒントType-Hinting Dependencies

コマンドの引数とオプションに付け加え、コマンドクロージャはタイプヒントによる追加の依存を受け取り、それらはサービスコンテナにより依存解決されます。In addition to receiving your command's arguments and options, command Closures may also type-hint additional dependencies that you would like resolved out of the service container[/docs/{{version}}/container]:

use App\User;
use App\DripEmailer;

Artisan::command('email:send {user}', function (DripEmailer $drip, $user) {
    $drip->send(User::find($user));
});

クロージャコマンドの説明Closure Command Descriptions

クロージャベースコマンドの定義時には、コマンドの説明を追加するためにdescribeメソッドを使います。この説明はphp artisan listphp artisan helpコマンド実行時に表示されます。When defining a Closure based command, you may use the describe method to add a description to the command. This description will be displayed when you run the php artisan list or php artisan help commands:

Artisan::command('build {project}', function ($project) {
    $this->info("Building {$project}!");
})->describe('Build the project');

コマンドライン指定の定義Defining Input Expectations

コンソールコマンドを書く場合、引数やオプションによりユーザから情報を入力してもらうのが一般的です。コマンドのsignatureプロパティにユーザに期待する入力を記述することにより、Laravelではとても便利に定義できます。signatureプロパティー1行でわかりやすいルート定義のような記法により、コマンドの名前と引数、オプションを定義できます。When writing console commands, it is common to gather input from the user through arguments or options. Laravel makes it very convenient to define the input you expect from the user using the signature property on your commands. The signature property allows you to define the name, arguments, and options for the command in a single, expressive, route-like syntax.

引数Arguments

ユーザから入力してもらう引数とオプションは全て波括弧で囲みます。以下の例の場合、必須のuserコマンド引数を定義しています。All user supplied arguments and options are wrapped in curly braces. In the following example, the command defines one required argument: user:

/**
 * コンソールコマンドの名前と引数、オプション
 *
 * @var string
 */
protected $signature = 'email:send {user}';

任意の引数やデフォルト値を指定することも可能です。You may also make arguments optional and define default values for arguments:

// 任意指定な引数
email:send {user?}

// デフォルト値を持つ、任意指定な引数
email:send {user=foo}

オプションOptions

オプションも引数と同様にユーザからの入力です。コマンドラインで指定する場合、2つのハイフン(--)を先頭に付けます。値を取るものと、取らないもの、2つのタイプのオプションがあります。値を取らないオプションは、論理的な「スイッチ」として動作します。このタイプのオプションを確認しましょう。Options, like arguments, are another form of user input. Options are prefixed by two hyphens (--) when they are specified on the command line. There are two types of options: those that receive a value and those that don't. Options that don't receive a value serve as a boolean "switch". Let's take a look at an example of this type of option:

/**
 * コンソールコマンドの名前と引数、オプション
 *
 * @var string
 */
protected $signature = 'email:send {user} {--queue}';

この例の場合、Artisanコマンド起動時に、--queueスイッチを指定できるようになります。--queueスイッチが指定されると、オプションの値はtrueになります。そうでなければ、値はfalseになります。In this example, the --queue switch may be specified when calling the Artisan command. If the --queue switch is passed, the value of the option will be true. Otherwise, the value will be false:

php artisan email:send 1 --queue

値を取るオプションOptions With Values

次に、ユーザによる値の入力を基体するオプションを確認しましょう。ユーザによりオプションの値の指定が必要である場合、オプション名は=記号ではじめます。Next, let's take a look at an option that expects a value. If the user must specify a value for an option, suffix the option name with a = sign:

/**
 * コンソールコマンドの名前と引数、オプション
 *
 * @var string
 */
protected $signature = 'email:send {user} {--queue=}';

この例では、次のようにオプションに値を指定します。In this example, the user may pass a value for the option like so:

php artisan email:send 1 --queue=default

オプション名の後に値を指定することにより、オプションのデフォルト値を指定できます。ユーザにより値が指定されない場合、デフォルト値が指定されます。You may assign default values to options by specifying the default value after the option name. If no option value is passed by the user, the default value will be used:

email:send {user} {--queue=default}

オプションショートカットOption Shortcuts

オプション定義時にショートカットを割りつけるには、完全なオプション名の前に|で区切り、ショートカットを指定してください。To assign a shortcut when defining an option, you may specify it before the option name and use a | delimiter to separate the shortcut from the full option name:

email:send {user} {--Q|queue}

入力配列Input Arrays

引数やオプションで、配列による入力を定義したい場合は、*文字を使います。最初に引数の配列指定の例を、見てみましょう。If you would like to define arguments or options to expect array inputs, you may use the * character. First, let's take a look at an example that specifies an array argument:

email:send {user*}

このメソッド呼び出し時に、user引数はコマンドラインの順番に渡されます。以下のコマンドは、user['foo', 'bar']をセットします。When calling this method, the user arguments may be passed in order to the command line. For example, the following command will set the value of user to ['foo', 'bar']:

php artisan email:send foo bar

オプションの配列入力を定義する場合、各値はオプション名を付けて指定する必要があります。When defining an option that expects an array input, each option value passed to the command should be prefixed with the option name:

email:send {user} {--id=*}

php artisan email:send --id=1 --id=2

入力の説明Input Descriptions

入力の引数とオプションの説明をパラメータと説明をコロンで分けることで指定できます。コマンドを定義するため、もう少し余裕が欲しければ、定義を複数行へ自由に分割してください。You may assign descriptions to input arguments and options by separating the parameter from the description using a colon. If you need a little extra room to define your command, feel free to spread the definition across multiple lines:

/**
 * コンソールコマンドの名前と引数、オプション
 *
 * @var string
 */
protected $signature = 'email:send
                        {user : The ID of the user}
                        {--queue= : Whether the job should be queued}';

コマンドI/OCommand I/O

入力の取得Retrieving Input

コマンド実行時に指定された引数やオプションの値にアクセスする必要が明らかにあります。そのために、argumentoptionメソッドを使用して下さい。While your command is executing, you will obviously need to access the values for the arguments and options accepted by your command. To do so, you may use the argument and option methods:

/**
 * コンソールコマンドの実行
 *
 * @return mixed
 */
public function handle()
{
    $userId = $this->argument('user');

    //
}

全引数を「配列」で受け取りたければ、argumentを呼んでください。If you need to retrieve all of the arguments as an array, call the arguments method:

$arguments = $this->arguments();

引数と同様、とても簡単にoptionメソッドでオプションを取得できます。argumentメソッドと同じように呼びだせば、全オプションを「配列」で取得できます。Options may be retrieved just as easily as arguments using the option method. To retrieve all of the options as an array, call the options method:

// 特定オプションの取得
$queueName = $this->option('queue');

// 全オプションの取得
$options = $this->options();

引数やオプションが存在していない場合、nullが返されます。If the argument or option does not exist, null will be returned.

入力のプロンプトPrompting For Input

コマンドラインに付け加え、コマンド実行時にユーザに入力を尋ねることもできます。askメソッドにユーザへ表示する質問を指定すると、ユーザに入力してもらい、その後値がコマンドに返ってきます。In addition to displaying output, you may also ask the user to provide input during the execution of your command. The ask method will prompt the user with the given question, accept their input, and then return the user's input back to your command:

/**
 * コンソールコマンドの実行
 *
 * @return mixed
 */
public function handle()
{
    $name = $this->ask('What is your name?');
}

secretメソッドもaskと似ていますが、コンソールでユーザがタイプした値を表示しません。このメソッドはパスワードのような機密情報を尋ねるときに便利です。The secret method is similar to ask, but the user's input will not be visible to them as they type in the console. This method is useful when asking for sensitive information such as a password:

$password = $this->secret('What is the password?');

確認Asking For Confirmation

単純にユーザから確認を取りたい場合は、confirmメソッドを使ってください。このメソッドはデフォルトでfalseを返します。プロンプトに対してyyesが入力されると、trueを返します。If you need to ask the user for a simple confirmation, you may use the confirm method. By default, this method will return false. However, if the user enters y or yes in response to the prompt, the method will return true.

if ($this->confirm('Do you wish to continue?')) {
    //
}

自動補完Auto-Completion

anticipateメソッドは可能性のある選択肢の、自動補完機能を提供するために使用します。ユーザは表示される自動補完の候補にかかわらず、どんな答えも返答できます。The anticipate method can be used to provide auto-completion for possible choices. The user can still choose any answer, regardless of the auto-completion hints:

$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);

複数選択の質問Multiple Choice Questions

あらかじめ決められた選択肢をユーザから選んでもらいたい場合は、choiceメソッドを使用します。何も選ばれなかった場合に返ってくるデフォルト値を指定することも可能です。If you need to give the user a predefined set of choices, you may use the choice method. You may set the default value to be returned if no option is chosen:

$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $default);

出力の書き出しWriting Output

コンソールに出力するには、lineinfocommentquestionerrorメソッドを使います。その名前が表す目的で使用し、それぞれ適当なANSIカラーが表示に使われます。たとえば、全般的な情報をユーザへ表示しましょう。通常、infoメソッドはコンソールに緑の文字で表示します。To send output to the console, use the line, info, comment, question and error methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let's display some general information to the user. Typically, the info method will display in the console as green text:

/**
 * コンソールコマンドの実行
 *
 * @return mixed
 */
public function handle()
{
    $this->info('Display this on the screen');
}

エラーメッセージを表示する場合は、errorメソッドです。エラーメッセージは通常赤で表示されます。To display an error message, use the error method. Error message text is typically displayed in red:

$this->error('Something went wrong!');

プレーンな、色を使わずにコンソール出力する場合は、lineメソッドを使います。If you would like to display plain, uncolored console output, use the line method:

$this->line('Display this on the screen');

テーブルレイアウトTable Layouts

tableメソッドにより簡単に正しくデータの複数行/カラムをフォーマットできます。メソッドにヘッダと行を渡してください。幅と高さは与えたデータから動的に計算されます。The table method makes it easy to correctly format multiple rows / columns of data. Just pass in the headers and rows to the method. The width and height will be dynamically calculated based on the given data:

$headers = ['Name', 'Email'];

$users = App\User::all(['name', 'email'])->toArray();

$this->table($headers, $users);

プログレスバーProgress Bars

時間がかかるタスクでは、進捗状況のインディケータを表示できると便利です。出力のオブジェクトを使用し、プログレスバーを開始、進行、停止することができます。最初に、処理全体を繰り返す総ステップ数を定義します。それから、各アイテムの処理の後に、プログレスバーを進めます。For long running tasks, it could be helpful to show a progress indicator. Using the output object, we can start, advance and stop the Progress Bar. First, define the total number of steps the process will iterate through. Then, advance the Progress Bar after processing each item:

$users = App\User::all();

$bar = $this->output->createProgressBar(count($users));

foreach ($users as $user) {
    $this->performTask($user);

    $bar->advance();
}

$bar->finish();

より詳細なオプションに関しては、Symfonyのプログレスバーコンポーネントのドキュメントで確認してください。For more advanced options, check out the Symfony Progress Bar component documentation[https://symfony.com/doc/2.7/components/console/helpers/progressbar.html].

コマンド登録Registering Commands

コマンドが完成したら、Artisanに登録する必要があります。全コマンドはapp/Console/Kernel.phpファイルの中で登録されています。このファイルのcommandsプロパティで、コマンドがリストされているのに気がつくと思います。コマンドを登録するには、ただコマンドクラス名をリストに追加するだけです。Artisanが起動した時点でこのプロパティーの全コマンドはサービスコンテナにより依存解決され、Artisanへ登録されます。Once your command is finished, you need to register it with Artisan. All commands are registered in the app/Console/Kernel.php file. Within this file, you will find a list of commands in the commands property. To register your command, simply add the command's class name to the list. When Artisan boots, all the commands listed in this property will be resolved by the service container[/docs/{{version}}/container] and registered with Artisan:

protected $commands = [
    Commands\SendEmails::class
];

プログラムによるコマンド実行Programmatically Executing Commands

ArtisanコマンドをCLI以外から実行したい場合もあるでしょう。たとえばルートやコントローラーからArtisanコマンドを起動したい場合です。Artisanファサードのcallメソッドで実行できます。callメソッドでは第1引数にコマンド名を指定します。第2引数にコマンドのパラメーターを配列で指定します。exitコードが返されます。Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the call method on the Artisan facade to accomplish this. The call method accepts the name of the command as the first argument, and an array of command parameters as the second argument. The exit code will be returned:

Route::get('/foo', function () {
    $exitCode = Artisan::call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});

Artisanファサードのqueueメソッドを使用すると、キューワーカーによりバックグラウンドでArtisanコマンドが実行されるようにキューされます。このメソッドを使用する前に、キューの設定を確実に済ませ、キューリスナを実行してください。Using the queue method on the Artisan facade, you may even queue Artisan commands so they are processed in the background by your queue workers[/docs/{{version}}/queues]. Before using this method, make sure you have configured your queue and are running a queue listener:

Route::get('/foo', function () {
    Artisan::queue('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});

migrate:refreshコマンドの--forceフラッグのように、文字列を受け取らないオプションの値を指定する必要がある場合は、論理値でtruefalseを指定します。If you need to specify the value of an option that does not accept string values, such as the --force flag on the migrate:refresh command, you may pass true or false:

$exitCode = Artisan::call('migrate:refresh', [
    '--force' => true,
]);

他のコマンドからの呼び出しCalling Commands From Other Commands

存在するArtisanコマンドから別のコマンドを呼び出したい場合もあるでしょう。callメソッドで実行できます。このcallメソッドへは、コマンド名とコマンドパラメーターの配列を指定します。Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the call method. This call method accepts the command name and an array of command parameters:

/**
 * コンソールコマンドの実行
 *
 * @return mixed
 */
public function handle()
{
    $this->call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
}

他のコンソールコマンドを実行しつつ、出力を全て無視したい場合は、callSilentメソッドを使用してください。callSilentメソッドの使い方は、callメソッドと同じです。If you would like to call another console command and suppress all of its output, you may use the callSilent method. The callSilent method has the same signature as the call method:

$this->callSilent('email:send', [
    'user' => 1, '--queue' => 'default'
]);

章選択

開発環境
ビューとテンプレート
公式パッケージ

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作