[Intermediate Laravel] 10-The-Seeds-for-Database-Seeding

來源:互聯網
上載者:User

簡介

我們繼續承接上節課說的,接著學習 Database-Seeding 的工作原理:

Database-Seeding 命令列參數

首先,我們執行 php artisan help db:seed 看看發生什麼,結果如所示:

預設情況下,我們沒有寫 –class 參數即啟動 seeder,會自動調用 DatabaseSeeder;

SeedCommand Seed命令列

通過 IDE(猜測類名為SeederCommand或位置) 定位到 SeedCommad.php ,執行入口方法為 fire() 後續會詳細說明,先總體瞭解類中方法,具體代碼及注釋如下:

class SeedCommand extends Command{  //引用確認提示  use ConfirmableTrait;   /**   * The console command name.   *   * @var string   */  protected $name = 'db:seed';   /**   * The console command description.   *   * @var string   */  protected $description = 'Seed the database with records';   /**   * The connection resolver instance.   *   * @var \Illuminate\Database\ConnectionResolverInterface   */  protected $resolver;   /**   * Create a new database seed command instance.   *   * @param  \Illuminate\Database\ConnectionResolverInterface $resolver   * @return void   */  public function __construct(Resolver $resolver)  {    parent::__construct();     $this->resolver = $resolver;  }   /**   * Execute the console command.   * 執行console命令列   * @return void   */  public function fire()  {    if (!$this->confirmToProceed()) {      return;    }     $this->resolver->setDefaultConnection($this->getDatabase());    // 擷取相應 Seeder,並調用其 run 方法    $this->getSeeder()->run();  }   /**   * Get a seeder instance from the container.   * 擷取輸入的class參數,   * @return \Illuminate\Database\Seeder   */  protected function getSeeder()  {    // 從輸入的class參數,擷取Seeder;相當於App::make('className'),預設為 DatabaseSeeder    $class = $this->laravel->make($this->input->getOption('class'));     return $class->setContainer($this->laravel)->setCommand($this);  }   /**   * Get the name of the database connection to use.   * 擷取要使用的資料庫連結名稱   * @return string   */  protected function getDatabase()  {    // 擷取輸入database 參數值    $database = $this->input->getOption('database');    // 如果沒有輸入database 參數值,則擷取設定檔中預設資料庫即config\database.php中default參數value    return $database ?: $this->laravel['config']['database.default'];  }   /**   * Get the console command options.   * 擷取console命令列參數   * @return array   */  protected function getOptions()  {    return [      ['class', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder', 'DatabaseSeeder'],       ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed'],       ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'],    ];  }} 

fire 方法

使用者執行 console 命令,即調用 SeedCommand 類中 fire 方法,fire 方法中先通過引用 use ConfirmableTrait , 調用相關 confirmToProceed 方法,來確認是否繼續,具體代碼及注釋如下:

trait ConfirmableTrait{  /**   * Confirm before proceeding with the action.   * 在進行動作之前確認   * @param  string $warning   * @param  \Closure|bool|null $callback   * @return bool   */  public function confirmToProceed($warning = 'Application In Production!', $callback = null)  {    // 擷取預設確認資訊,如果$callback為空白則尋找預設環境變數,production則為ture    $callback = is_null($callback) ? $this->getDefaultConfirmCallback() : $callback;    // 是否需要確認資訊    $shouldConfirm = $callbackinstanceof Closure ? call_user_func($callback) : $callback;     if ($shouldConfirm) {      // 如果參數有force,則直接返回true,標識已確認      if ($this->option('force')) {        return true;      }      // 輸出確認提示警示資訊      $this->comment(str_repeat('*', strlen($warning) + 12));      $this->comment('*     ' . $warning . '     *');      $this->comment(str_repeat('*', strlen($warning) + 12));      $this->output->writeln('');       $confirmed = $this->confirm('Do you really wish to run this command? [y/N]');      // 通過使用者輸入的y或者n判斷是否執行      if (!$confirmed) {        $this->comment('Command Cancelled!');         return false;      }    }     return true;  }   /**   * Get the default confirmation callback.   *   * @return \Closure   */  protected function getDefaultConfirmCallback()  {    return function () {      //判斷容器環境是否=production(即.env中APP_ENV對應值),等於則返回true      return $this->getLaravel()->environment() == 'production';    };  }} 

將.env中的APP_ENV值由預設local置為production,執行 php artisan db:seed ,結果如所示:

執行 php artisan db:seed --force 則跳過提示,直接執行 seed 命令。

DatabaseSeeder預設Seeder

命令 php artisan db:seed 預設執行 DatabaseSeeder 中的 run 方法,回頭來看下call方法如何執行:

class DatabaseSeeder extends Seeder{   protected $toTruncate = ['users','lessons'];   /**   * Run the database seeds.   *   * @return void   */  public function run()  {    Model::unguard();    // 迴圈刪除表    foreach($this->toTruncateas $table)    {      DB::table($table)->truncate();    }    // 調用Seeder父類中 call 方法:    $this->call('UsersTableSeeder');    $this->call('LessonsTableSeeder');  }} 

Seed 類中 call 和 resolve 方法:

/*** Seed類中call方法* Seed the given connection from the given path.* 通過給出的路徑進行seed操作* @param  string $class* @return void*/public function call($class){    // 容器存在則App::make($class)->run(),否則new一個$class,調用run    $this->resolve($class)->run();    // 通過接受$class,輸出執行Seeded的類名    if (isset($this->command)) {        $this->command->getOutput()->writeln("Seeded: $class");    }} /*** Resolve an instance of the given seeder class.* 擷取一個給定seeder類的執行個體* @param  string $class* @return \Illuminate\Database\Seeder*/protected function resolve($class){    if (isset($this->container)) {        $instance = $this->container->make($class);        $instance->setContainer($this->container);    } else {        $instance = new $class;    }     if (isset($this->command)) {        $instance->setCommand($this->command);    }    return $instance;} 
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.