イントロダクションIntroduction
Artisan(アーティザン:職人)とはLaravelを構成しているコマンドラインインターフェイスの名前です。アプリケーション開発で役立つ数多くのコマンドを用意しています。パワフルなSymfonyコンソールコンポーネントを利用し動いています。利用可能なArtisanコマンドの全リストを確認するには、list
コマンドを使用してください。Artisan is the name of the
command-line interface included with Laravel. It
provides a number of helpful commands for your use
while developing your application. It is driven by
the powerful Symfony Console component. 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.json
で設定しコマンドがオートロードされる限り、どこにでも好きな場所に置くことができます。In addition to the commands
provided with Artisan, you may also build your own
custom commands for working with your application.
You may store your custom commands in the
app/Console/Commands
directory;
however, you are free to choose your own storage
location as long as your commands can be autoloaded
based on your composer.json
settings.
新しいコマンドを生成するにはArtisanコマンドのmake:console
を使用し、開発に取り掛かるために便利なコマンドのひな形を生成してください。To create a new command, you may
use the make:console
Artisan command,
which will generate a command stub to help you get
started:
php artisan make:console SendEmails
上のコマンドはapp/Console/Commands/SendEmails.php
にクラスを生成します。生成時に--command
オプションを使用すれば、コマンド名を指定することができます。The command above would generate
a class at
app/Console/Commands/SendEmails.php
.
When creating the command, the
--command
option may be used to assign
the terminal command name:
php artisan make:console SendEmails --command=emails:send
コマンド構造Command Structure
コマンドが生成できたら、list
スクリーンでそのコマンドが表示できるように、クラスのsignature
とdescription
プロパティを指定してください。Once your command is generated,
you should fill out the signature
and
description
properties of the class,
which will be used when displaying your command on
the list
screen.
handle
メソッドがコマンド実行時に呼び出されます。このメソッドにどんなコマンドロジックも置くことができます。サンプルのコマンドを見てみましょう。The handle
method
will be called when your command is executed. You
may place any command logic in this method. Let's
take a look at an example command.
コマンドのコンストラクターで必要な依存を注入できることに注目しましょう。Laravelのサービスコンテナはコンストラクタでタイプヒントにより指定された依存を全て自動的に注入します。コードの再利用性を高めるためにコンソールコマンドを軽く保ち、アプリケーションサービスにそのタスクを達成させるのを遅らせるのは、グッドプラクティスです。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. For greater code reusability, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks.
<?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')));
}
}
コマンドI/OCommand I/O
入力エクスペクションの定義Defining Input Expectations
コンソールコマンドを書く場合、引数やオプションによりユーザーから情報を入力してもらうのは一般的です。コマンドのsignature
プロパティにユーザーに期待する入力を記述することにより、Laravelではとても便利に定義できます。signature
プロパティー一行でわかりやすいルート定義のような記法により、コマンドの名前と引数、オプションを定義できます。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.
ユーザーから入力してもらう引数とオプションは全て波括弧で囲みます。以下の例の場合、必須の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 optional arguments:
// 任意の引数…
email:send {user?}
// 任意の引数とデフォルト値…
email:send {user=foo}
オプションも引数と同様にユーザーからの入力です。しかし、コマンドラインで指定する場合、2つのハイフン(--
)を先頭に付けます。ですからオプション定義も同じように行います。Options, like arguments, are also
a form of user input. However, they are prefixed by
two hyphens (--
) when they are
specified on the command line. We can define options
in the signature like so:
/**
* コンソールコマンドの名前と引数、オプション
*
* @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
ユーザーにより値を指定してもらうオプションを指定することもでき、オプション名の最後に=
記号を付けてください。You may also specify that the
option should be assigned a value by the user by
suffixing the option name with a =
sign, indicating that a value should be
provided:
/**
* コンソールコマンドの名前と引数、オプション
*
* @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 also assign default values to options:
email:send {user} {--queue=default}
オプション定義時にショートカットを割りつけるには、完全なオプション名の前に|で区切り、ショートカットを指定してください。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 Descriptions
入力の引数とオプションの説明をコロンで分けて指定できます。You may assign descriptions to input arguments and options by separating the parameter from the description using a colon:
/**
* コンソールコマンドの名前と引数、オプション
*
* @var string
*/
protected $signature = 'email:send
{user : The ID of the user}
{--queue= : Whether the job should be queued}';
入力の取得Retrieving Input
コマンド実行時に指定された引数やオプションの値にアクセスする必要が明らかにあります。そのために、argument
とoption
メソッドを使用して下さい。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:
引数の値を取得するには、argument
を使用します。To retrieve the value of an
argument, use the argument
method:
/**
* コンソールコマンドの実行
*
* @return mixed
*/
public function handle()
{
$userId = $this->argument('user');
//
}
全引数を「配列」で受け取りたければ、引数を付けずにargument
を呼んでください。If you need to retrieve all of
the arguments as an array
, call
argument
with no parameters:
$arguments = $this->argument();
引数と同様、とても簡単にoption
メソッドでオプションを取得できます。argument
メソッドと同じように引数を付けずに呼びだせば、全オプションを「配列」で取得できます。Options may be retrieved just as
easily as arguments using the option
method. Like the argument
method, you
may call option
without any parameters
in order to retrieve all of the options as an
array
:
// 特定のオプションの取得…
$queueName = $this->option('queue');
// 全オプションの取得…
$options = $this->option();
引数やオプションが存在していない場合、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
を返します。プロンプトに対してy
を入力すると、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
in response to the prompt, the
method will return true
.
if ($this->confirm('Do you wish to continue? [y|N]')) {
//
}
ユーザーによる選択Giving The User A Choice
anticipate
メソッドは可能性がある選択肢に対して自動補完を提供します。ユーザーは選択肢にかかわらず、どんな答えも選ぶことができます。The anticipate
method can be used to provided autocompletion for
possible choices. The user can still choose any
answer, regardless of the choices.
$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);
あらかじめ決められた選択肢をユーザーから選んでもらいたい場合は、choice
メソッドを使用します。ユーザーは答えのインデックスを選びますが、答えの値が返ってきます。何も選ばれなかった場合に返ってくるデフォルト値を指定することも可能です。If you need to give the user a
predefined set of choices, you may use the
choice
method. The user chooses the
index of the answer, but the value of the answer
will be returned to you. You may set the default
value to be returned if nothing is
chosen:
$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], false);
出力の書き出しWriting Output
コンソールに出力するには、line
、info
、comment
、question
、error
メソッドを使います。その名前が表す目的で使用し、それぞれ適当なANSIカラーが表示に使われます。To send output to the console,
use the line
, info
,
comment
, question
and
error
methods. Each of these methods
will use the appropriate ANSI colors for their
purpose.
ユーザーにメッセージを知らせる場合は、info
メソッドを使用します。通常、これにより緑のテキストがコンソールに表示されます。To display an information message
to the user, use the info
method.
Typically, this will display in the console as green
text:
/**
* コンソールコマンドの実行
*
* @return mixed
*/
public function handle()
{
$this->info('これがスクリーンに表示される');
}
エラーメッセージを表示する場合は、error
メソッドです。エラーメッセージは通常赤で表示されます。To display an error message, use
the error
method. Error message text is
typically displayed in red:
$this->error('何かがおかしい!');
プレーンなコンソール出力を行いたい場合は、line
メソッドを使います。line
メソッドは表示に特定の色を利用しません。If you want to display plain
console output, use the line
method.
The line
method does not receive any
unique coloration:
$this->line('これがスクリーンに表示される');
テーブルレイアウト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. You have to define the number of steps when you start the progress, then advance the Progress Bar after each step:
$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[http://symfony.com/doc/2.7/components/console/helpers/progressbar.html].
コマンド登録Registering Commands
コマンドが出来上がり、使用できるようにするにはArtisanへ登録する必要があります。app/Console/Kernel.php
ファイルで行います。Once your command is finished,
you need to register it with Artisan so it will be
available for use. This is done within the
app/Console/Kernel.php
file.
このファイルのcommands
プロパティでコマンドがリストされているのに気がつくでしょう。コマンドを登録するには、ただクラス名をリストに追加するだけです。Artisanが起動した時点でこのプロパティーの全コマンドはサービスコンテナにより依存解決され、Artisanへ登録されます。Within this file, you will find a
list of commands in the commands
property. To register your command, simply add the
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
];
コードからのコマンド呼び出しCalling Commands Via Code
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]:
Route::get('/foo', function () {
Artisan::queue('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
});
migrate:refresh
コマンドの--force
フラッグのように、文字列を受け取らないオプションの値を指定する必要がある場合は、論理値でtrue
やfalse
を指定します。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 a
boolean 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'
]);