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

PHP에서, 특성은 방법 재사용이 필요하지만 상속에 적합하지 않은 상황에 적합합니다. 1) 특성은 클래스에서 다중 상속의 복잡성을 피할 수 있도록 수많은 방법을 허용합니다. 2) 특성을 사용할 때는 대안과 키워드를 통해 해결할 수있는 방법 충돌에주의를 기울여야합니다. 3) 성능을 최적화하고 코드 유지 보수성을 향상시키기 위해 특성을 과도하게 사용해야하며 단일 책임을 유지해야합니다.

의존성 주입 컨테이너 (DIC)는 PHP 프로젝트에 사용하기위한 객체 종속성을 관리하고 제공하는 도구입니다. DIC의 주요 이점에는 다음이 포함됩니다. 1. 디커플링, 구성 요소 독립적 인 코드는 유지 관리 및 테스트가 쉽습니다. 2. 유연성, 의존성을 교체 또는 수정하기 쉽습니다. 3. 테스트 가능성, 단위 테스트를 위해 모의 객체를 주입하기에 편리합니다.

SplfixedArray는 PHP의 고정 크기 배열로, 고성능 및 메모리 사용이 필요한 시나리오에 적합합니다. 1) 동적 조정으로 인한 오버 헤드를 피하기 위해 생성 할 때 크기를 지정해야합니다. 2) C 언어 배열을 기반으로 메모리 및 빠른 액세스 속도를 직접 작동합니다. 3) 대규모 데이터 처리 및 메모리에 민감한 환경에 적합하지만 크기가 고정되어 있으므로주의해서 사용해야합니다.

PHP는 $ \ _ 파일 변수를 통해 파일 업로드를 처리합니다. 보안을 보장하는 방법에는 다음이 포함됩니다. 1. 오류 확인 확인, 2. 파일 유형 및 크기 확인, 3 파일 덮어 쓰기 방지, 4. 파일을 영구 저장소 위치로 이동하십시오.

JavaScript에서는 NullCoalescingOperator (??) 및 NullCoalescingAssignmentOperator (?? =)를 사용할 수 있습니다. 1. 2. ??= 변수를 오른쪽 피연산자의 값에 할당하지만 변수가 무효 또는 정의되지 않은 경우에만. 이 연산자는 코드 로직을 단순화하고 가독성과 성능을 향상시킵니다.

CSP는 XSS 공격을 방지하고 리소스로드를 제한하여 웹 사이트 보안을 향상시킬 수 있기 때문에 중요합니다. 1.CSP는 HTTP 응답 헤더의 일부이며 엄격한 정책을 통해 악의적 인 행동을 제한합니다. 2. 기본 사용법은 동일한 원점에서 자원을로드 할 수있는 것입니다. 3. 고급 사용량은 특정 도메인 이름을 스크립트와 스타일로드 할 수 있도록하는 것과 같은보다 세밀한 전략을 설정할 수 있습니다. 4. Content-Security Policy 보고서 전용 헤더를 사용하여 CSP 정책을 디버그하고 최적화하십시오.

HTTP 요청 방법에는 각각 리소스를 확보, 제출, 업데이트 및 삭제하는 데 사용되는 Get, Post, Put and Delete가 포함됩니다. 1. GET 방법은 리소스를 얻는 데 사용되며 읽기 작업에 적합합니다. 2. 게시물은 데이터를 제출하는 데 사용되며 종종 새로운 리소스를 만드는 데 사용됩니다. 3. PUT 방법은 리소스를 업데이트하는 데 사용되며 완전한 업데이트에 적합합니다. 4. 삭제 방법은 자원을 삭제하는 데 사용되며 삭제 작업에 적합합니다.

HTTPS는 HTTP를 기반으로 보안 계층을 추가하는 프로토콜로, 주로 암호화 된 데이터를 통해 사용자 개인 정보 및 데이터 보안을 보호합니다. 작업 원칙에는 TLS 핸드 셰이크, 인증서 확인 및 암호화 된 커뮤니케이션이 포함됩니다. HTTP를 구현할 때는 인증서 관리, 성능 영향 및 혼합 콘텐츠 문제에주의를 기울여야합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경

뜨거운 주제



