2017-02-09 159 views
0

我想教自己Laravel命令,以便稍後使用它來安排它們。這是我的內核文件:從控制檯調用laravel artisan命令

namespace App\Console; 

    use Illuminate\Console\Scheduling\Schedule; 
    use Illuminate\Foundation\Console\Kernel as ConsoleKernel; 

    class Kernel extends ConsoleKernel 
    { 
     /** 
     * The Artisan commands provided by your application. 
     * 
     * @var array 
     */ 
     protected $commands = [ 
      // 
      'App\Console\Commands\FooCommand',  
     ]; 

     /** 
     * Define the application's command schedule. 
     * 
     * @param \Illuminate\Console\Scheduling\Schedule $schedule 
     * @return void 
     */ 
     protected function schedule(Schedule $schedule) 
     { 
      // $schedule->command('inspire') 
      //   ->hourly(); 
      $schedule->command('App\Console\Commands\FooCommand')->hourly(); 
     } 

     /** 
     * Register the Closure based commands for the application. 
     * 
     * @return void 
     */ 
     protected function commands() 
     { 
      require base_path('routes/console.php'); 
     } 
    } 

這是\軟件\控制檯\命令

namespace App\Console\Commands; 

use Illuminate\Console\Command; 

class FooCommand extends Command 
{ 
    /** 
    * The name and signature of the console command. 
    * 
    * @var string 
    */ 
    protected $signature = 'command:name'; 

    /** 
    * The console command description. 
    * 
    * @var string 
    */ 
    protected $description = 'Command description'; 

    /** 
    * Create a new command instance. 
    * 
    * @return void 
    */ 
    public function __construct() 
    { 
     parent::__construct(); 
    } 

    /** 
    * Execute the console command. 
    * 
    * @return mixed 
    */ 
    public function handle() 
    { 
     // 
    } 

    public function fire() 
    { 

     $this->info('Test has fired.'); 
    } 
} 

我想測試FooCommand命令裏面的命令文件。它如何從shell調用這個命令,以便結果是「Test has fired。」?

回答

2

手動運行您的命令:php artisan command:name

刪除你的fire功能,你可以在裏面處理這個handle函數。

在內核級

class Kernel extends ConsoleKernel 
{ 
    .... 

    protected function schedule(Schedule $schedule) 
    { 
     $schedule->command('command:name') 
      ->hourly(); 
    } 
} 

修復你的日程安排功能要配置您的日程安排,請閱讀本: https://laravel.com/docs/5.4/scheduling

+0

感謝您的答覆。如果我添加另一個命令文件如「SecondCommand」?我怎麼稱呼它? – user7432810

+0

'schedule:run'命令將執行在'schedule'函數中註冊的所有命令。只需添加一個新命令,如'$ schedule-> command('command:name') - > hourly();'schedule'函數內部。 – MarcosRJJunior