定义预期的输入 在你编写控制台命令时,通常通过参数和选项收集用户输入,Laravel 使这项操作变得很方便,你可以在命令里使用 signature 属性。 signature 属性通过一个类似路由风格的语法让用户为命令定义名称,参数和选项。
参数 所有用户提供的参数及选项都包在大括号中。如以下例子,此命令会定义一个 必须 的参数: user :
/**
* The name and signature of the console command.
*
* @var string
*/protected $signature = 'email:send {user}';
您也可以创建可选参数,并定义参数的默认值:
// Optional argument...email:send {user?}// Optional argument with default value...email:send {user=foo}
选项 选项,和参数一样,也是用户输入的一种格式,不过当使用选项时,需要在命令前加两个连字符号 (--) 的前缀,有两种类型的选项:接收一个值和不接受值。选项不接收一个值作为布尔值的 switch 。让我们看一个选项的例子:
/**
* The name and signature of the console command.
*
* @var string
*/protected $signature = 'email:send {user} {--queue}';
在这个例子中,当调用 Artisan 命令时,--queue 这个选项可以被明确的指定。如果 --queue 被当成输入时,这个选项的的值为 true ,否则这个值为 false :
php artisan email:send 1 --queue
有值的选项 接下来,我们看下有值的选项。如果用户必须为选项指定一个值,会在选项的后面加一个 = 的后缀:
/**
* The name and signature of the console command.
*
* @var string
*/protected $signature = 'email:send {user} {--queue=}';
在这个例子中, 用户可以想下面这个例子传递一个值:
php artisan email:send 1 --queue=default
您可以通过指定选项名称后的默认值将默认值分配给选项。如果用户没有输入一个值,将会采用默认的值:
email:send {user} {--queue=default}
选项快捷键 当定义一个定义选项时,可以分配一个快捷键。你可以在选项前使用一个 | 分隔符将简写和完整选项名分开:
email:send {user} {--Q|queue}
数组输入 如果你想使用数组输入方式定义参数或选项,你可以使用 * 符号。首先,我们先看一个数组输入的实例:
email:send {user*}
调用此方法时,user 参数通过命令行输入。例如,下面这个命令将会为 user 设置 ['foo', 'bar'] :
php artisan email:send foo bar
在定义一个使用数组输入时,每个输入选项值的命令都要在选项名称前加前缀:
email:send {user} {--id=*}php artisan email:send --id=1 --id=2
输入描述 您可以通过在使用一个冒号分离参数来分配输入参数和选项的说明。如果你需要一个小的额外的空间来定义你的命令,可以多行定义你的扩展:
/**
* The name and signature of the console command.
*
* @var string
*/protected $signature = 'email:send {user : The ID of the user}{--queue= : Whether the job should be queued}';
有时候你可能希望在 CLI 之外执行 Artisan 命令,例如,你可能希望在路由或控制器中触发 Artisan 命令,你可以使用 Artisan facade 上的 call 方法来完成。call 方法接收被执行的命令名称作为第一个参数,命令参数数组作为第二个参数,退出代码被返回:
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--queue' => 'default'
]);
//});
