search
HomeBackend DevelopmentPHP Tutorial[Intermediate Laravel] 10-The-Seeds-for-Database-Seeding

简介

我们继续承接上节课说的,接着学习 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("<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;} 

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools