イントロダクションIntroduction
ArtisanはLaravelが用意しているコマンドラインインターフェイスです。Artisanは、アプリケーションのルートにartisanスクリプトとして存在し、アプリケーションの構築に役立つコマンドを多数提供しています。使用可能なすべてのArtisanコマンドのリストを表示するには、listコマンドを使用してください。Artisan is the command line
interface included with Laravel. Artisan exists at
the root of your application as the
artisan script and 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, precede the name of the command
with help:
php artisan help migrate
Laravel SailLaravel Sail
ローカル開発環境としてLaravel
Sailを使用している場合は、必ずsailコマンドラインを使用してArtisanコマンドを呼び出してください。Sailは、アプリケーションのDockerコンテナ内でArtisanコマンドを実行します。If you are using Laravel
Sail[/docs/{{version}}/sail] as your local
development environment, remember to use the
sail command line to invoke Artisan
commands. Sail will execute your Artisan commands
within your application's Docker
containers:
./vendor/bin/sail artisan list
Tinker(REPL)Tinker (REPL)
Laravel Tinkerは、PsySHパッケージを搭載したLaravelフレームワークの強力なREPLです。Laravel Tinker is a powerful REPL for the Laravel framework, powered by the PsySH[https://github.com/bobthecow/psysh] package.
インストールInstallation
すべてのLaravelアプリケーションにはデフォルトでTinkerが含まれています。ただし、以前にアプリケーションからTinkerを削除した場合は、Composerを使用してTinkerをインストールできます。All Laravel applications include Tinker by default. However, you may install Tinker using Composer if you have previously removed it from your application:
composer require laravel/tinker
Note: Laravelアプリケーションを操作するときに、ホットリロード、複数行のコード編集、自動補完をお求めですか?Tinkerwellをチェックしてみてください![!NOTE]
Looking for hot reloading, multiline code editing, and autocompletion when interacting with your Laravel application? Check out Tinkerwell[https://tinkerwell.app]!
使用法Usage
Tinkerを使用すると、Eloquentモデル、ジョブ、イベントなどを含む、コマンドラインでLaravelアプリケーション全体を操作できます。Tinker環境に入るには、tinkerArtisanコマンドを実行します。Tinker allows you to interact
with your entire Laravel application on the command
line, including your Eloquent models, jobs, events,
and more. To enter the Tinker environment, run the
tinker Artisan command:
php artisan tinker
vendor:publishコマンドを使用してTinkerの設定ファイルをリソース公開できます。You can publish Tinker's
configuration file using the
vendor:publish command:
php artisan vendor:publish --provider="Laravel\Tinker\TinkerServiceProvider"
Warning!
dispatchヘルパ関数とDispatchableクラスのdispatchメソッドは、ジョブをキューに投入するのにガベージコレクションへ依存しています。したがって、Tinkerを使う場合は、Bus::dispatchまたはQueue::pushを使用してジョブをディスパッチする必要があります。[!WARNING]
Thedispatchhelper function anddispatchmethod on theDispatchableclass depends on garbage collection to place the job on the queue. Therefore, when using tinker, you should useBus::dispatchorQueue::pushto dispatch jobs.
コマンド許可リストCommand Allow List
Tinkerは「許可」リストを利用して、シェル内で実行できるArtisanコマンドを決定します。デフォルトでは、clear-compiled、down、env、inspire、migrate、optimize、upコマンドを実行できます。より多くのコマンドを許可したい場合は、それらをtinker.php設定ファイルのcommands配列に追加してください。Tinker utilizes an
"allow" list to determine which Artisan
commands are allowed to be run within its shell. By
default, you may run the
clear-compiled, down,
env, inspire,
migrate, optimize, and
up commands. If you would like to allow
more commands you may add them to the
commands array in your
tinker.php configuration
file:
'commands' => [
// App\Console\Commands\ExampleCommand::class,
],
エイリアスするべきではないクラスClasses That Should Not Be Aliased
通常、Tinkerでクラスを操作すると、Tinkerはクラスへ自動的にエイリアスを付けます。ただし、一部のクラスをエイリアスしないことをお勧めします。これは、tinker.php設定ファイルのdont_alias配列にクラスをリストすることで実現できます。Typically, Tinker automatically
aliases classes as you interact with them in Tinker.
However, you may wish to never alias some classes.
You may accomplish this by listing the classes in
the dont_alias array of your
tinker.php configuration
file:
'dont_alias' => [
App\Models\User::class,
],
コマンド記述Writing Commands
Artisanが提供するコマンドに加え、独自のカスタムコマンドを作成することもできます。コマンドは通常、app/Console/Commandsディレクトリに保存します。ただし、Composerでコマンドをロードできる限り、独自の保存場所を自由に選択できます。In addition to the commands
provided with Artisan, you may 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, you may
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 - it will be created the first time you
run the make:command Artisan
command:
php artisan make:command SendEmails
コマンド構造Command Structure
コマンドを生成した後に、クラスのsignatureプロパティとdescriptionプロパティに適切な値を定義する必要があります。これらのプロパティは、list画面にコマンドを表示するときに使用されます。signatureプロパティを使用すると、コマンドの入力期待値を定義することもできます。コマンドの実行時にhandleメソッドが呼び出されます。このメソッドにコマンドロジックを配置できます。After generating your command,
you should define appropriate values for the
signature and description
properties of the class. These properties will be
used when displaying your command on the
list screen. The signature
property also allows you to define your command's
input
expectations[#defining-input-expectations].
The handle method will be called when
your command is executed. You may place your command
logic in this method.
コマンドの例を見てみましょう。コマンドのhandleメソッドを介して必要な依存関係の注入を要求できることに注意してください。Laravelサービスコンテナは、このメソッドの引数でタイプヒントされているすべての依存関係を自動的に注入します。Let's take a look at an example
command. Note that we are able to request any
dependencies we need via the command's
handle method. The Laravel service
container[/docs/{{version}}/container] will
automatically inject all dependencies that are
type-hinted in this method's signature:
<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Support\DripEmailer;
use Illuminate\Console\Command;
class SendEmails extends Command
{
/**
* コンソールコマンドの名前と使い方
*
* @var string
*/
protected $signature = 'mail:send {user}';
/**
* コンソールコマンドの説明
*
* @var string
*/
protected $description = 'Send a marketing email to a user';
/**
* consoleコマンドの実行
*/
public function handle(DripEmailer $drip): void
{
$drip->send(User::find($this->argument('user')));
}
}
Note: コードの再利用性を上げるには、コンソールコマンドを軽くし、アプリケーションサービスに任せてタスクを実行することをお勧めします。上記の例では、電子メールを送信する「手間のかかる作業」を行うためにサービスクラスを挿入していることに注意してください。[!NOTE]
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 above, note that we inject a service class to do the "heavy lifting" of sending the e-mails.
クロージャコマンドClosure Commands
クロージャベースのコマンドは、コンソールコマンドをクラスとして定義する代替として提供しています。ルートクロージャがコントローラの代わりであるのと同様に、コマンドクロージャはコマンドクラスの代わりであると考えてください。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.
routes/console.phpファイルではHTTPルートを定義しませんが、アプリケーションのコンソールベースのエントリポイント(ルート)を定義しています。Artisan::commandメソッドを使用して、このファイル内でクロージャベースのコンソールコマンドをすべて定義できます。commandメソッドは2つ引数を取り、コマンド使用定義と、コマンドの引数とオプションを受け取るクロージャです。Even though the
routes/console.php file 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
console commands using the
Artisan::command method. The
command method accepts two arguments:
the command
signature[#defining-input-expectations] and
a closure which receives the command's arguments and
options:
Artisan::command('mail:send {user}', function (string $user) {
$this->info("Sending email to: {$user}!");
});
クロージャは基になるコマンドインスタンスにバインドされているため、通常は完全なコマンドクラスでアクセスできるすべてのヘルパメソッドに完全にアクセスできます。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\Models\User;
use App\Support\DripEmailer;
Artisan::command('mail:send {user}', function (DripEmailer $drip, string $user) {
$drip->send(User::find($user));
});
クロージャコマンドの説明Closure Command Descriptions
クロージャベースのコマンドを定義するときは、purposeメソッドを使用してコマンドに説明を追加できます。この説明は、php
artisan listまたはphp artisan
helpコマンドを実行すると表示されます。When defining a closure based
command, you may use the purpose 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('mail:send {user}', function (string $user) {
// ...
})->purpose('Send a marketing email to a user');
単一インスタンスコマンドIsolatable Commands
Warning! この機能を利用するには、アプリケーションで
memcached、redis、dynamodb、database、file、arrayキャッシュドライバをアプリケーションのデフォルトキャッシュドライバとして使用する必要があります。さらに、すべてのサーバから同一のセントルキャッシュサーバと通信する必要があります。[!WARNING]
To utilize this feature, your application must be using thememcached,redis,dynamodb,database,file, orarraycache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server.
同時に実行できるコマンドのインスタンスが1つだけであることを保証したい場合があります。これを実現するには、コマンドクラスでIlluminate\Contracts\Console\Isolatableインターフェイスを実装します。Sometimes you may wish to ensure
that only one instance of a command can run at a
time. To accomplish this, you may implement the
Illuminate\Contracts\Console\Isolatable
interface on your command class:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Isolatable;
class SendEmails extends Command implements Isolatable
{
// ...
}
コマンドをIsolatableとマークすると、Laravel
は自動的にコマンドに--isolatedオプションを追加します。このオプションでコマンドを呼び出すと、Laravelはそのコマンドの他のインスタンスが既に実行されていないことを確認します。Laravelは、アプリケーションのデフォルトキャッシュドライバを使用してアトミックロックの取得を試みることで、この機能を実現します。コマンドの他のインスタンスが実行されている場合、コマンドは実行されませんが、コマンドは正常終了ステータスコードで終了します。When a command is marked as
Isolatable, Laravel will automatically
add an --isolated option to the
command. When the command is invoked with that
option, Laravel will ensure that no other instances
of that command are already running. Laravel
accomplishes this by attempting to acquire an atomic
lock using your application's default cache driver.
If other instances of the command are running, the
command will not execute; however, the command will
still exit with a successful exit status
code:
php artisan mail:send 1 --isolated
コマンドが実行できなかった場合に返される終了ステータスコードを指定したい場合は、isolatedオプションで希望するステータスコードを指定できます。If you would like to specify the
exit status code that the command should return if
it is not able to execute, you may provide the
desired status code via the isolated
option:
php artisan mail:send 1 --isolated=12
Lock IDLock ID
デフォルトでLaravelは、コマンド名を使用し、アプリケーションのキャッシュでアトミック・ロックを取得するために使用する文字列キーを生成します。しかし、ArtisanコマンドクラスへisolatableIdメソッドを定義すれば、このキーをカスタマイズでき、コマンドの引数やオプションをキーへ統合できます。By default, Laravel will use the
command's name to generate the string key that is
used to acquire the atomic lock in your
application's cache. However, you may customize this
key by defining an isolatableId method
on your Artisan command class, allowing you to
integrate the command's arguments or options into
the key:
/**
* コマンドの一意的なIDを取得
*/
public function isolatableId(): string
{
return $this->argument('user');
}
ロックの有効時間Lock Expiration Time
デフォルトでは、単一コマンドのロックは、コマンド終了後に期限切れとなります。あるいは、コマンドが中断されて終了できなかった場合は、ロックは1時間後に期限切れになります。しかし、コマンドでisolationLockExpiresAtメソッドを定義すれば、ロックの有効期限を調整できます。By default, isolation locks
expire after the command is finished. Or, if the
command is interrupted and unable to finish, the
lock will expire after one hour. However, you may
adjust the lock expiration time by defining a
isolationLockExpiresAt method on your
command:
use DateTimeInterface;
use DateInterval;
/**
* 単一コマンドのロック期限を決定
*/
public function isolationLockExpiresAt(): DateTimeInterface|DateInterval
{
return now()->addMinutes(5);
}
入力期待値の定義Defining Input Expectations
コンソールコマンドを作成する場合、引数またはオプションを介してユーザーからの入力を収集するのが一般的です。Laravelを使用すると、コマンドのsignatureプロパティを使用して、ユーザーへ期待する入力を定義するのが非常に便利になります。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.
引数Arguments
ユーザーが指定できるすべての引数とオプションは、中括弧で囲います。次の例では、コマンドは1つの必須引数、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 = 'mail:send {user}';
引数をオプションにしたり、引数のデフォルト値を定義したりもできます。You may also make arguments optional or define default values for arguments:
// オプションの引数
'mail:send {user?}'
// オプションの引数とデフォルト値
'mail:send {user=foo}'
オプションOptions
引数のようにオプションは、ユーザー入力の別の形態です。オプションは、コマンドラインで指定する場合、接頭辞として2つのハイフン(--)を付けます。オプションには、値を受け取るオプションと受け取らないオプションの2種類があります。値を受け取らないオプションは、論理「スイッチ」として機能します。このタイプのオプションの例を見てみましょう。Options, like arguments, are
another form of user input. Options are prefixed by
two hyphens (--) when they are provided
via 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 = 'mail: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 mail: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, you should suffix the
option name with a = sign:
/**
* コンソールコマンドの名前と使い方
*
* @var string
*/
protected $signature = 'mail:send {user} {--queue=}';
この例で、ユーザーはオプションとして値を渡すことができます。コマンドの起動時にオプションが指定されていない場合、その値は「null」になります。In this example, the user may
pass a value for the option like so. If the option
is not specified when invoking the command, its
value will be null:
php artisan mail: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:
'mail:send {user} {--queue=default}'
オプションのショートカットOption Shortcuts
オプションを定義するときにショートカットを割り当てるには、オプション名の前にショートカットを指定し、|文字を区切り文字として使用してショートカットと完全なオプション名を分けます。To assign a shortcut when
defining an option, you may specify it before the
option name and use the | character as
a delimiter to separate the shortcut from the full
option name:
'mail:send {user} {--Q|queue}'
ターミナルでコマンドを起動する場合、オプションのショートカットの先頭にハイフンを1つ付け、オプションの値を指定する際は=文字をつけないでください。When invoking the command on your
terminal, option shortcuts should be prefixed with a
single hyphen and no = character should
be included when specifying a value for the
option:
php artisan mail:send 1 -Qdefault
入力配列Input Arrays
複数の入力値を期待する引数またはオプションを定義する場合は、*文字を使用できます。まず、そのような引数を指定する例を見てみましょう。If you would like to define
arguments or options to expect multiple input
values, you may use the * character.
First, let's take a look at an example that
specifies such an argument:
'mail:send {user*}'
このメソッドを呼び出すときは、コマンドラインへ順番に、user引数を渡せます。たとえば、次のコマンドは、userの値に1と2の値を配列に設定します。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
an array with 1 and 2 as
its values:
php artisan mail:send 1 2
この*文字をオプションの引数定義と組み合わせ、引数を0個以上許可することができます。This * character can
be combined with an optional argument definition to
allow zero or more instances of an
argument:
'mail:send {user?*}'
オプション配列Option Arrays
複数の入力値を期待するオプションを定義する場合、コマンドに渡たす各オプション値には、オプション名のプレフィックスを付ける必要があります。When defining an option that expects multiple input values, each option value passed to the command should be prefixed with the option name:
'mail:send {--id=*}'
このコマンドは、複数の--id引数を渡し、起動できます。Such a command may be invoked by
passing multiple --id
arguments:
php artisan mail:send --id=1 --id=2
入力の説明Input Descriptions
コロンを使用して引数名と説明を区切ることにより、入力引数とオプションに説明を割り当てることができます。コマンドを定義するために少し余分なスペースが必要な場合は、定義を自由に複数の行に分けてください。You may assign descriptions to input arguments and options by separating the argument name 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 = 'mail:send
{user : The ID of the user}
{--queue : Whether the job should be queued}';
入力不足のプロンプトPrompting for Missing Input
コマンドが必須の引数を持っている場合に、その引数が指定されないとエラーメッセージを表示します。もしくは、PromptsForMissingInputインターフェイスを実装し、必要な引数がない場合に自動でユーザーにプロンプトを表示するように、コマンドを設定してください。If your command contains required
arguments, the user will receive an error message
when they are not provided. Alternatively, you may
configure your command to automatically prompt the
user when required arguments are missing by
implementing the PromptsForMissingInput
interface:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\PromptsForMissingInput;
class SendEmails extends Command implements PromptsForMissingInput
{
/**
* コンソールコマンドの名前と使い方
*
* @var string
*/
protected $signature = 'mail:send {user}';
// ...
}
Laravelが必要な引数をユーザーから収集する必要がある場合、引数名か説明のどちらかを使用し、インテリジェントに質問のフレーズを作り、自動的にユーザーへ尋ねます。必要な引数を収集するために使用する質問をカスタマイズしたい場合は、引数名をキーにした質問の配列を返す、promptForMissingArgumentsUsingメソッドを実装してください。If Laravel needs to gather a
required argument from the user, it will
automatically ask the user for the argument by
intelligently phrasing the question using either the
argument name or description. If you wish to
customize the question used to gather the required
argument, you may implement the
promptForMissingArgumentsUsing method,
returning an array of questions keyed by the
argument names:
/**
* リターンする質問を使い、足りない入力引数をプロンプトする
*
* @return array<string, string>
*/
protected function promptForMissingArgumentsUsing(): array
{
return [
'user' => 'Which user ID should receive the mail?',
];
}
質問とプレースホルダを含むタプルを使用して、プレースホルダ・テキストを提供することもできます。You may also provide placeholder text by using a tuple containing the question and placeholder:
return [
'user' => ['Which user ID should receive the mail?', 'E.g. 123'],
];
プロンプトを完全にコントロールしたい場合は、ユーザーへプロンプトを表示し、その答えを返すクロージャを指定してください。If you would like complete control over the prompt, you may provide a closure that should prompt the user and return their answer:
use App\Models\User;
use function Laravel\Prompts\search;
// ...
return [
'user' => fn () => search(
label: 'Search for a user:',
placeholder: 'E.g. Taylor Otwell',
options: fn ($value) => strlen($value) > 0
? User::where('name', 'like', "%{$value}%")->pluck('name', 'id')->all()
: []
),
];
Note: 包括的なLaravel Promptsドキュメントに、利用可能なプロンプトとその使用方法に関する追加情報を用意してあります。[!NOTE]
The comprehensive Laravel Prompts[/docs/{{version}}/prompts] documentation includes additional information on the available prompts and their usage.
オプションの選択や入力をユーザーに促したい場合は、コマンドのhandleメソッドにプロンプトを含めてください。引数が足りない場合にのみプロンプトを出したい場合は、afterPromptingForMissingArgumentsメソッドを実装してください:If you wish to prompt the user to
select or enter options[#options], you may
include prompts in your command's
handle method. However, if you only
wish to prompt the user when they have also been
automatically prompted for missing arguments, then
you may implement the
afterPromptingForMissingArguments
method:
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use function Laravel\Prompts\confirm;
// ...
/**
* 足りない引数をユーザーへ促した後に実行するアクション
*/
protected function afterPromptingForMissingArguments(InputInterface $input, OutputInterface $output): void
{
$input->setOption('queue', confirm(
label: 'Would you like to queue the mail?',
default: $this->option('queue')
));
}
コマンドI/OCommand I/O
入力の取得Retrieving Input
コマンドの実行中に、コマンドが受け入れた引数とオプションの値にアクセスする必要があるでしょう。これには、argumentメソッドとoptionメソッドを使用します。引数またはオプションが存在しない場合、nullが返されます。While your command is executing,
you will likely 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. If an argument or
option does not exist, null will be
returned:
/**
* consoleコマンドの実行
*/
public function handle(): void
{
$userId = $this->argument('user');
}
すべての引数をarrayとして取得する必要がある場合は、argumentsメソッドを呼び出します。If you need to retrieve all of
the arguments as an array, call the
arguments method:
$arguments = $this->arguments();
オプションは、optionメソッドを使用して引数と同じように簡単に取得できます。すべてのオプションを配列として取得するには、optionsメソッドを呼び出します。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();
入力のプロンプトPrompting for Input
Note: Laravel Prompts は、美しくユーザーフレンドリーなUIをコマンドラインアプリケーションに追加するためのPHPパッケージで、プレースホルダテキストやバリデーションなどのブラウザライクな機能を備えています。[!NOTE]
Laravel Prompts[/docs/{{version}}/prompts] is a PHP package for adding beautiful and user-friendly forms to your command-line applications, with browser-like features including placeholder text and validation.
出力の表示に加えて、コマンドの実行中にユーザーへ入力を提供するように依頼することもできます。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:
/**
* consoleコマンドの実行
*/
public function handle(): void
{
$name = $this->ask('What is your name?');
// ...
}
askメソッドは、第2引数もオプションで引数に取ります。この第2引数には、ユーザー入力がない場合に返すデフォルト値を指定します。The ask method also
accepts an optional second argument which specifies
the default value that should be returned if no user
input is provided:
$name = $this->ask('What is your name?', 'Taylor');
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 passwords:
$password = $this->secret('What is the password?');
確認を求めるAsking for Confirmation
単純な「はい」か「いいえ」の確認をユーザーに求める必要がある場合は、「confirm」メソッドを使用します。デフォルトでは、このメソッドはfalseを返します。ただし、ユーザーがプロンプトに応答して「y」または「yes」を入力すると、メソッドは「true」を返します。If you need to ask the user for a
simple "yes or no" 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?')) {
// ...
}
必要に応じて、confirmメソッドの2番目の引数としてtrueを渡すことにより、確認プロンプトがデフォルトでtrueを返すように指定できます。If necessary, you may specify
that the confirmation prompt should return
true by default by passing
true as the second argument to the
confirm method:
if ($this->confirm('Do you wish to continue?', true)) {
// ...
}
オートコンプリートAuto-Completion
anticipateメソッドを使用して、可能な選択肢のオートコンプリートを提供できます。オートコンプリートのヒントに関係なく、ユーザーは引き続き任意の回答ができます。The anticipate
method can be used to provide auto-completion for
possible choices. The user can still provide any
answer, regardless of the auto-completion
hints:
$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);
もしくはanticipateメソッドの2番目の引数としてクロージャを渡すこともできます。クロージャは、ユーザーが入力文字を入力するたびに呼び出されます。クロージャは、これまでのユーザーの入力を含む文字列パラメーターを受け取り、オートコンプリートのオプションの配列を返す必要があります。Alternatively, you may pass a
closure as the second argument to the
anticipate method. The closure will be
called each time the user types an input character.
The closure should accept a string parameter
containing the user's input so far, and return an
array of options for auto-completion:
$name = $this->anticipate('What is your address?', function (string $input) {
// オートコンプリートオプションを返す…
});
複数の選択肢の質問Multiple Choice Questions
質問をするときにユーザーに事前定義された選択肢のセットを提供する必要がある場合は、choiceメソッドを使用します。メソッドに3番目の引数としてインデックスを渡すことにより、オプションが選択されていない場合に返されるデフォルト値の配列インデックスを設定できます。If you need to give the user a
predefined set of choices when asking a question,
you may use the choice method. You may
set the array index of the default value to be
returned if no option is chosen by passing the index
as the third argument to the method:
$name = $this->choice(
'What is your name?',
['Taylor', 'Dayle'],
$defaultIndex
);
さらに、choiceメソッドは、有効な応答を選択するための最大試行回数と、複数の選択が許可されるかどうかを決定するために、オプションとして4番目と5番目の引数を取ります。In addition, the
choice method accepts optional fourth
and fifth arguments for determining the maximum
number of attempts to select a valid response and
whether multiple selections are
permitted:
$name = $this->choice(
'What is your name?',
['Taylor', 'Dayle'],
$defaultIndex,
$maxAttempts = null,
$allowMultipleSelections = false
);
出力の書き込みWriting Output
コンソールに出力を送信するには、line、info、comment、question、warn、errorメソッドを使用できます。これらの各メソッドは、目的に応じて適切なANSIカラーを使用します。たとえば、一般的な情報をユーザーに表示してみましょう。通常、infoメソッドはコンソールに緑色のテキストを表示します。To send output to the console,
you may use the line,
info, comment,
question, warn, 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 colored
text:
/**
* consoleコマンドの実行
*/
public function handle(): void
{
// ...
$this->info('The command was successful!');
}
エラーメッセージを表示するには、errorメソッドを使用します。エラーメッセージのテキストは通常、赤で表示します。To display an error message, use
the error method. Error message text is
typically displayed in red:
$this->error('Something went wrong!');
lineメソッドを使用して、色のないプレーンなテキストを表示できます。You may use the line
method to display plain, uncolored text:
$this->line('Display this on the screen');
newLineメソッドを使用して空白行を表示できます。You may use the
newLine method to display a blank
line:
// 空白行を1行書く
$this->newLine();
// 空白行を3行書く
$this->newLine(3);
テーブルTables
tableメソッドを使用すると、データの複数の行/列を簡単に正しくフォーマットできます。
テーブルの列名とデータを入力するだけで、Laravelがテーブルの適切な幅と高さを自動的に計算します。
use App\Models\User;
$this->table(
['Name', 'Email'],
User::all(['name', 'email'])->toArray()
);
プログレスバーProgress Bars
長時間実行されるタスクの場合、タスクの完了度をユーザーに通知する進行状況バーを表示すると便利です。withProgressBarメソッドを使用するとLaravelは、進行状況バーを表示し、指定した反復可能値を反復するごとにその進捗を進めます。For long running tasks, it can be
helpful to show a progress bar that informs users
how complete the task is. Using the
withProgressBar method, Laravel will
display a progress bar and advance its progress for
each iteration over a given iterable
value:
use App\Models\User;
$users = $this->withProgressBar(User::all(), function (User $user) {
$this->performTask($user);
});
場合によっては、プログレスバーの進め方を手作業で制御する必要があります。最初に、プロセスが繰り返すステップの総数を定義します。次に、各アイテムを処理した後、プログレスバーを進めます。Sometimes, you may need more manual control over how a progress bar is advanced. First, define the total number of steps the process will iterate through. Then, advance the progress bar after processing each item:
$users = App\Models\User::all();
$bar = $this->output->createProgressBar(count($users));
$bar->start();
foreach ($users as $user) {
$this->performTask($user);
$bar->advance();
}
$bar->finish();
Note: より高度なオプションについては、Symfonyのプログレスバーコンポーネントのドキュメントをご覧ください。[!NOTE]For more advanced options, check out the Symfony Progress Bar component documentation[https://symfony.com/doc/7.0/components/console/helpers/progressbar.html].
コマンド登録Registering Commands
Laravelはデフォルトで、自動的にapp/Console/Commandsディレクトリ内の全てのコマンドを登録します。しかし、アプリケーションのbootstrap/app.phpファイル内のwithCommandsメソッドを使用すれば、他のディレクトリをスキャンし、Artisanコマンドを探すようLaravelに指示できます。By default, Laravel automatically
registers all commands within the
app/Console/Commands directory.
However, you can instruct Laravel to scan other
directories for Artisan commands using the
withCommands method in your
application's bootstrap/app.php
file:
->withCommands([
__DIR__.'/../app/Domain/Orders/Commands',
])
必要であれば、withCommandsメソッドへコマンドのクラス名を与え、手作業でコマンドを登録することもできます。If necessary, you may also
manually register commands by providing the
command's class name to the
withCommands method:
use App\Domain\Orders\Commands\SendEmails;
->withCommands([
SendEmails::class,
])
Artisanが起動すると、アプリケーション内のすべてのコマンドがサービスコンテナによって解決され、Artisanに登録されます。When Artisan boots, all the commands in your application will be resolved by the service container[/docs/{{version}}/container] and registered with Artisan.
プログラムからのコマンド実行Programmatically Executing Commands
CLIの外部でArtisanコマンドを実行したい場合があります。たとえば、ルートまたはコントローラからArtisanコマンドを実行したい場合があります。これを実現するには、Artisanファサードのcallメソッドを使用します。callメソッドは、最初の引数としてコマンドの名前またはクラス名のいずれかを受け入れ、2番目の引数としてコマンドパラメータの配列を取ります。終了コードが返されます:Sometimes you may wish to execute
an Artisan command outside of the CLI. For example,
you may wish to execute 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 either the command's signature name
or class name as its first argument, and an array of
command parameters as the second argument. The exit
code will be returned:
use Illuminate\Support\Facades\Artisan;
Route::post('/user/{user}/mail', function (string $user) {
$exitCode = Artisan::call('mail:send', [
'user' => $user, '--queue' => 'default'
]);
// ...
});
または、Artisanコマンド全体を文字列としてcallメソッドに渡すこともできます。Alternatively, you may pass the
entire Artisan command to the call
method as a string:
Artisan::call('mail:send 1 --queue=default');
配列値の受け渡しPassing Array Values
コマンドで配列を受け入れるオプションを定義している場合は、値の配列をそのオプションに渡すことができます。If your command defines an option that accepts an array, you may pass an array of values to that option:
use Illuminate\Support\Facades\Artisan;
Route::post('/mail', function () {
$exitCode = Artisan::call('mail:send', [
'--id' => [5, 13]
]);
});
論理値値の受け渡しPassing Boolean Values
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 should
pass true or false as the
value of the option:
$exitCode = Artisan::call('migrate:refresh', [
'--force' => true,
]);
Artisanコマンドのキュー投入Queueing Artisan Commands
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:
use Illuminate\Support\Facades\Artisan;
Route::post('/user/{user}/mail', function (string $user) {
Artisan::queue('mail:send', [
'user' => $user, '--queue' => 'default'
]);
// ...
});
onConnectionおよびonQueueメソッドを使用して、Artisanコマンドをディスパッチする接続やキューを指定できます。Using the
onConnection and onQueue
methods, you may specify the connection or queue the
Artisan command should be dispatched to:
Artisan::queue('mail:send', [
'user' => 1, '--queue' => 'default'
])->onConnection('redis')->onQueue('commands');
他コマンドからのコマンド呼び出し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 arguments /
options:
/**
* consoleコマンドの実行
*/
public function handle(): void
{
$this->call('mail:send', [
'user' => 1, '--queue' => 'default'
]);
// ...
}
別のコンソールコマンドを呼び出してその出力をすべて抑制したい場合は、callSilentlyメソッドを使用できます。callSilentlyメソッドはcallメソッドと同じ使い方です。If you would like to call another
console command and suppress all of its output, you
may use the callSilently method. The
callSilently method has the same
signature as the call
method:
$this->callSilently('mail:send', [
'user' => 1, '--queue' => 'default'
]);
シグナルの処理Signal Handling
ご存知のように、オペレーティングシステムでは、実行中のプロセスにシグナルを送ることができます。例えば、SIGTERMシグナルはオペレーティングシステムがプログラムを終了するように要求する方法です。もし、Artisanコンソールコマンドでシグナルをリッスンし、発生時にコードを実行したい場合は、trapメソッドを使用してください。As you may know, operating
systems allow signals to be sent to running
processes. For example, the SIGTERM
signal is how operating systems ask a program to
terminate. If you wish to listen for signals in your
Artisan console commands and execute code when they
occur, you may use the trap
method:
/**
* consoleコマンドの実行
*/
public function handle(): void
{
$this->trap(SIGTERM, fn () => $this->shouldKeepRunning = false);
while ($this->shouldKeepRunning) {
// ...
}
}
一度に複数のシグナルをリッスンするには、trapメソッドへシグナルの配列を指定してください。To listen for multiple signals at
once, you may provide an array of signals to the
trap method:
$this->trap([SIGTERM, SIGQUIT], function (int $signal) {
$this->shouldKeepRunning = false;
dump($signal); // SIGTERM / SIGQUIT
});
スタブのカスタマイズStub Customization
Artisanコンソールのmakeコマンドは、コントローラ、ジョブ、マイグレーション、テストなどのさまざまなクラスを作成するために使用されます。これらのクラスは、入力に基づいた値が挿入される「スタブ」ファイルを使用して生成されます。ただし、Artisanにより生成されるファイルへ小さな変更を加えることをおすすめします。このためには、stub:publishコマンドを使用して、最も一般的なスタブをアプリケーションにリソース公開し、カスタマイズできるようにします。The Artisan console's
make commands are used to create a
variety of classes, such as controllers, jobs,
migrations, and tests. These classes are generated
using "stub" files that are populated with
values based on your input. However, you may want to
make small changes to files generated by Artisan. To
accomplish this, you may use the
stub:publish command to publish the
most common stubs to your application so that you
can customize them:
php artisan stub:publish
リソース公開するスタブは、アプリケーションのルートのstubsディレクトリ内へ設置します。これらのスタブに加えた変更は、Artisanのmakeコマンドを使用して対応するクラスを生成するときに反映されます。The published stubs will be
located within a stubs directory in the
root of your application. Any changes you make to
these stubs will be reflected when you generate
their corresponding classes using Artisan's
make commands.
イベントEvents
Artisanは、コマンドの実行時に、Illuminate\Console\Events\ArtisanStarting、Illuminate\Console\Events\CommandStarting、およびIlluminate\Console\Events\CommandFinishedの3つのイベントをディスパッチします。ArtisanStartingイベントは、Artisanが実行を開始するとすぐにディスパッチされます。次に、コマンドが実行される直前にCommandStartingイベントがディスパッチされます。最後に、コマンドの実行が終了すると、CommandFinishedイベントがディスパッチされます。Artisan dispatches three events
when running commands:
Illuminate\Console\Events\ArtisanStarting,
Illuminate\Console\Events\CommandStarting,
and
Illuminate\Console\Events\CommandFinished.
The ArtisanStarting event is dispatched
immediately when Artisan starts running. Next, the
CommandStarting event is dispatched
immediately before a command runs. Finally, the
CommandFinished event is dispatched
once a command finishes executing.