爲了建立一個新命令,你能夠使用Artisan中的 command:make
命令生成一個骨架做爲你的起點:php
生成一個命令類css
php artisan command:make FooCommand
默認狀況下,生成的類文件被存放在 app/commands
目錄下,同時你也能夠指定自定義目錄和命名空間:laravel
php artisan command:make FooCommand --path=app/classes --namespace=Classes
一旦你的命令完成後,你須要使用 Artisan 進行註冊,這樣纔可以被使用。這一般在 app/start/artisan.php
文件中完成。在這個文件中,你能夠使用 Artisan::add
函數註冊命令:app
註冊一個 Artisan 命令函數
Artisan::add(new CustomCommand);
若是你的命令在應用程序的 IoC 容器 中註冊,你能夠使用 Artisan::resolve
函數使它對 Artisan 可用:this
註冊一個在 IoC 容器中的命令spa
一個發郵件樣例:Artisan::resolve('binding.name');
<?php use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; class SendMailCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'SendMailCommand:sendMail';//命令名,命令行調用使用php artisian 這裏的$name值 /** * The console command description. * * @var string */ protected $description = 'send mail.'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { // $command=" C:/sendEmail -f from.sina.com -t to@qq.com -s smtp.sina.com -xu username -xp pasword -u test "; $message=$this->argument('message'); $str="$command -m $message "; $this->info($str); system($str); $this->info("It's Done, have a good day."); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( array('message', InputArgument::REQUIRED, 'An example argument.'), ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( //array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null), ); } }
運行:命令行
php artisan commanname argx --option=bar --option=baz
參考:code