[Intermediate Laravel] 10-the-seeds-for-database-seeding

Source: Internet
Author: User

Brief introduction

We continue to take the last class said, and then learn how database-seeding works:

database-seeding command-line arguments

First, we execute PHP artisan help db:seed See what happens and the results are as follows:

By default, we do not write –class parameters that start Seeder, and will automatically call Databaseseeder;

Seedcommand seed command Line

Navigate to seedcommad.php through the IDE (guessing the class name is Seedercommand or location), the execution of the Ingress Method for Fire () follow-up details, first the general understanding of the methods in the class, the specific code and comments are as follows:

Class Seedcommand extends command{//reference confirmation prompt 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 __construc     T (Resolver $resolver) {parent::__construct ();  $this->resolver = $resolver;   }/** * Execute the console command.    * Execute console command line * @return void */Public Function Fire () {if (! $this->confirmtoproceed ()) {return;    } $this->resolver->setdefaultconnection ($this->getdatabase ());  Get the corresponding Seeder and call its Run method $this->getseeder ()->run (); }   /**   * Get a Seeder instance from the container. * Get input class parameter, * @return \illuminate\database\seeder */protected function Getseeder () {//From input class parameter, get Seeder , equivalent to App::make (' ClassName '), the default is 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. * Gets the database link name to use * @return String */protected function getdatabase () {//Get input database parameter value $database = $this-&    Gt;input->getoption (' database '); If you do not enter the database parameter value, get the default parameter in the configuration file, which is config\database.php, the value return $database?: $this->laravel['  Config ' [' Database.default '];   }/** * Get the console command options. * Get console command line arguments * @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, ' F  Orce the operation to run if in production. '],];  }}

Fire method

The user executes the console command, which calls the fire method in the Seedcommand class, and the fire method, by referencing use confirmabletrait, calls the relevant Confirmtoproceed method to confirm the continuation, and the specific code and comments are as follows :

Trait confirmabletrait{/** * Confirm before proceeding with the action. * Confirm * @param string $warning * @param \closure|bool|null $callback * @return BOOL */Public Function Co Nfirmtoproceed ($warning = ' application in production! ', $callback = null) {//Get the default acknowledgement, if $callback is empty find the default environment variable, product Ion is ture $callback = Is_null ($callback)?    $this->getdefaultconfirmcallback (): $callback; Do I need to confirm the information $shouldConfirm = $callbackinstanceof Closure?     Call_user_func ($callback): $callback;      if ($shouldConfirm) {//If the argument has force, returns true immediately, identifying the confirmed if ($this->option (' Force ')) {return true;      }//Output Confirmation alert message $this->comment (str_repeat (' * ', strlen ($warning) + 12)); $this->comment (' * '. $warning.      '     *');      $this->comment (str_repeat (' * ', strlen ($warning) + 12));       $this->output->writeln ("); $confirmed = $this->confirm (' Does really wish to run the This command?      [y/n] '); Judging by the user's input of Y or NNo execute if (! $confirmed) {$this->comment (' Command cancelled! ');      return false;  }} return true;   }/** * Get the default confirmation callback. * * @return \closure */protected function Getdefaultconfirmcallback () {return function () {///Determine if the container environment is =pro    Duction (ie app_env corresponding value in. env), equal to return True return $this->getlaravel ()->environment () = = ' production ';  };  }}

The app_env value in. Env is set by the default local to production, which executes the PHP artisan Db:seed, as shown in the following:

Executing the PHP artisan db:seed--force Skips the hint and executes the seed command directly.

Databaseseeder Default Seeder

Command PHP artisan db:seed default execution of the Run method in Databaseseeder, looking back at how the call method executes:

Class Databaseseeder extends seeder{   protected $toTruncate = [' Users ', ' lessons '];   /**   * Run the database seeds.   *   * @return void */public  function run ()  {    model::unguard ();    Loop Delete Table    foreach ($this->totruncateas $table)    {      db::table ($table)->truncate ();    }    Call method in Seeder parent class:    $this->call (' Userstableseeder ');    $this->call (' Lessonstableseeder ');  

Call and resolve methods in the Seed class:

The call method in the/*** seed class * Seed the given connection from the given path.* seed operation by the given path * @param  string $class * @return void */public function Call ($class) {    //container exists App::make ($class)->run (), otherwise new one $class, calling run    $this->resolve ($class)->run ();    By accepting $class, the output executes seeded's class name    if (isset ($this->command)) {        $this->command->getoutput ()->writeln ("
 
  
   
  seeded:
 
   $class ");    }} /*** Resolve An instance of the given Seeder class.* gets an instance of a given Seeder class * @param  string $class * @return \illuminate\data base\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);    }    
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.