Table of Contents
简介
Database-Seeding 命令行参数
SeedCommand Seed命令行
fire 方法
DatabaseSeeder默认Seeder
Home Backend Development PHP Tutorial [Intermediate Laravel] 10-The-Seeds-for-Database-Seeding

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

Jun 23, 2016 pm 01:07 PM

简介

我们继续承接上节课说的,接着学习 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.'],    ];  }} 
Copy after login

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';    };  }} 
Copy after login

将.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');  }} 
Copy after login

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("<info>Seeded:</info> $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;} 
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles