$ ls crystal_folder

Laravel如何優雅地手加排程,順便看看PHP建構子相關

一個空的Laravel排程程式範例

<?php

namespace App\Console\Commands;
// import的小傢伙們(ry

class MyCMD extends Command
{

     /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cmd:our';

    // 命令desc
     /**
     * The console command description.
     *
     * @var string
     */
     protected $description = '這個排程的功能是阿巴阿巴..';

    // 建立實體+建構子注入Service
     protected $xxxService;
     /**
     * Create a new command instance.
     *
     * @return void
     */
     public function __construct(
          XxxService $xxxService
     ){
          parent::__construct();
          $this->xxxService = $xxxService;
          // 全域常數也能寫這邊~
     }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
      // 排程主要邏輯
      // 建議額外寫function在此呼叫
      $this->doSomething();

    }

    public function doSomething()
    {
      // doSomething
    }
}

最後記得到Kernel.php加入排程~

💭 Murmur
雖然大可不要注入Service、不經過Model執行DB操作-直接在`handle()`走起..!!
太陽一樣會升起~
但是...程式不美麗啊?!建議業務邏輯成熟後可以再拆回Service等地方改用依賴注入..
(其中感覺又以使用Model優先度比較高,直接寫SQL還挺不好看的...
Service看情形,如果有現成的就重用,太常見的考慮病回Service)

延伸閱讀

#Laravel #php