Laravel框架生命周期与原理分析

本文实例讲述了Laravel框架生命周期与原理。分享给大家供大家参考,具体如下:

引言:

如果你对一件工具的使用原理了如指掌,那么你在用这件工具的时候会充满信心!

正文:

一旦用户(浏览器)发送了一个HTTP请求,我们的apache或者Nginx一般都转到index.PHP,因此,之后的一系列步骤都是从index.PHP开始的,我们先来看一看这个文件代码

rush:PHP;"> make(Illuminate\Contracts\Http\Kernel::class); $response = $kernel->handle( $request = Illuminate\Http\Request::capture() ); $response->send(); $kernel->terminate($request,$response);

作者在注释里谈了kernel的作用,kernel的作用,kernel处理来访的请求,并且发送相应返回给用户浏览器。

这里又涉及到了一个app对象,所以附上app对象,所以附上app对象的源码,这份源码是PHP

rush:PHP;"> singleton( Illuminate\Contracts\Http\Kernel::class,App\Http\Kernel::class ); $app->singleton( Illuminate\Contracts\Console\Kernel::class,App\Console\Kernel::class ); $app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class,App\Exceptions\Handler::class ); /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app;

请看app变量是调用了这个类的构造函数,具体做了什么事,我们看源码。

setBasePath($basePath); } $this->registerBaseBindings(); $this->registerBaseServiceProviders(); $this->registerCoreContainerAliases(); }

构造器做了3件事,前两件事很好理解,创建Container,注册了ServiceProvider,看代码

instance('app',$this); $this->instance(Container::class,$this); } /** * Register all of the base service providers. * * @return void */ protected function registerBaseServiceProviders() { $this->register(new EventServiceProvider($this)); $this->register(new LogServiceProvider($this)); $this->register(new RoutingServiceProvider($this)); }

最后一件事,是做了个很大的数组,定义了大量的别名,侧面体现程序员是聪明的懒人。

[\Illuminate\Foundation\Application::class,\Illuminate\Contracts\Container\Container::class,\Illuminate\Contracts\Foundation\Application::class],'auth' => [\Illuminate\Auth\AuthManager::class,\Illuminate\Contracts\Auth\Factory::class],'auth.driver' => [\Illuminate\Contracts\Auth\Guard::class],'blade.compiler' => [\Illuminate\View\Compilers\BladeCompiler::class],'cache' => [\Illuminate\Cache\CacheManager::class,\Illuminate\Contracts\Cache\Factory::class],'cache.store' => [\Illuminate\Cache\Repository::class,\Illuminate\Contracts\Cache\Repository::class],'config' => [\Illuminate\Config\Repository::class,\Illuminate\Contracts\Config\Repository::class],'cookie' => [\Illuminate\Cookie\CookieJar::class,\Illuminate\Contracts\Cookie\Factory::class,\Illuminate\Contracts\Cookie\queueingFactory::class],'encrypter' => [\Illuminate\Encryption\Encrypter::class,\Illuminate\Contracts\Encryption\Encrypter::class],'db' => [\Illuminate\Database\DatabaseManager::class],'db.connection' => [\Illuminate\Database\Connection::class,\Illuminate\Database\ConnectionInterface::class],'events' => [\Illuminate\Events\dispatcher::class,\Illuminate\Contracts\Events\dispatcher::class],'files' => [\Illuminate\Filesystem\Filesystem::class],'filesystem' => [\Illuminate\Filesystem\FilesystemManager::class,\Illuminate\Contracts\Filesystem\Factory::class],'filesystem.disk' => [\Illuminate\Contracts\Filesystem\Filesystem::class],'filesystem.cloud' => [\Illuminate\Contracts\Filesystem\Cloud::class],'hash' => [\Illuminate\Contracts\Hashing\Hasher::class],'translator' => [\Illuminate\Translation\Translator::class,\Illuminate\Contracts\Translation\Translator::class],'log' => [\Illuminate\Log\Writer::class,\Illuminate\Contracts\Logging\Log::class,\Psr\Log\LoggerInterface::class],'mailer' => [\Illuminate\Mail\Mailer::class,\Illuminate\Contracts\Mail\Mailer::class,\Illuminate\Contracts\Mail\MailQueue::class],'auth.password' => [\Illuminate\Auth\Passwords\PasswordbrokerManager::class,\Illuminate\Contracts\Auth\PasswordbrokerFactory::class],'auth.password.broker' => [\Illuminate\Auth\Passwords\Passwordbroker::class,\Illuminate\Contracts\Auth\Passwordbroker::class],'queue' => [\Illuminate\Queue\QueueManager::class,\Illuminate\Contracts\Queue\Factory::class,\Illuminate\Contracts\Queue\Monitor::class],'queue.connection' => [\Illuminate\Contracts\Queue\Queue::class],'queue.failer' => [\Illuminate\Queue\Failed\FailedJobProviderInterface::class],'redirect' => [\Illuminate\Routing\Redirector::class],'redis' => [\Illuminate\Redis\RedisManager::class,\Illuminate\Contracts\Redis\Factory::class],'request' => [\Illuminate\Http\Request::class,\Symfony\Component\HttpFoundation\Request::class],'router' => [\Illuminate\Routing\Router::class,\Illuminate\Contracts\Routing\Registrar::class,\Illuminate\Contracts\Routing\BindingRegistrar::class],'session' => [\Illuminate\Session\SessionManager::class],'session.store' => [\Illuminate\Session\Store::class,\Illuminate\Contracts\Session\Session::class],'url' => [\Illuminate\Routing\UrlGenerator::class,\Illuminate\Contracts\Routing\UrlGenerator::class],'validator' => [\Illuminate\Validation\Factory::class,\Illuminate\Contracts\Validation\Factory::class],'view' => [\Illuminate\View\Factory::class,\Illuminate\Contracts\View\Factory::class],]; foreach ($aliases as $key => $aliases) { foreach ($aliases as $alias) { $this->alias($key,$alias); } } }

这里出现了一个instance函数,其实这并不是Application类的函数,而是Application类的父类Container类的函数

removeAbstractAlias($abstract); unset($this->aliases[$abstract]); // We'll check to determine if this type has been bound before,and if it has // we will fire the rebound callbacks registered with the container and it // can be updated with consuming classes that have gotten resolved here. $this->instances[$abstract] = $instance; if ($this->bound($abstract)) { $this->rebound($abstract); } }

Application是Container的子类,所以$app不仅是Application类的对象,还是Container的对象,所以,新出现的eton函数我们就可以到Container类的源代码文件里查。bind函数和singleton的区别见这篇博文。

eton这个函数,前一个参数是实际类名,后一个参数是类的“别名”。

$app对象声明了3个单例模型对象,分别是一个“别名”。

大家有没有发现,index.PHP中也有一个$kernel变量,但是只保存了make出来的HttpKernel变量,因此本文不再讨论,ConsoleKernel,ExceptionHandler。。。

继续在文件夹下找到PHP,既然我们把实际的HttpKernel做的事情都写在这PHP文件里,就从这份代码里看看究竟做了哪些事?

rush:PHP;"> [ \App\Http\Middleware\EncryptCookies::class,\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,\Illuminate\Session\Middleware\StartSession::class,\Illuminate\View\Middleware\ShareErrorsFromSession::class,\App\Http\Middleware\VerifyCsrftoken::class,],'api' => [ 'throttle:60,1',]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class,'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,'mymiddleware'=>\App\Http\Middleware\MyMiddleware::class,]; }

一目了然,HttpKernel里定义了中间件数组。

该做的做完了,就开始了请求到响应的过程,见index.PHP

handle( $request = Illuminate\Http\Request::capture() ); $response->send();

最后在中止,释放所有资源。

terminateMiddleware($request,$response); $this->app->terminate(); }

总结一下,简单归纳整个过程就是:

1.index.PHP加载PHP,在Application类的构造函数中创建Container,注册了ServiceProvider,定义了别名数组,然后用app变量保存构造函数构造出来的对象。

2.使用app这个对象,创建1个单例模式的对象HttpKernel,在创建HttpKernel时调用了构造函数,完成了中间件的声明。

3.以上这些工作都是在请求来访之前完成的,接下来开始等待请求,然后就是:

更多关于Laravel相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》及《PHP常见数据库操作技巧汇总》

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


今天windows 之家小编给大家介绍下在windows 中使用laravel安装homestead的操作方法!安装及配置:安装使用Vagrant安装Homestead盒子安装 Homestead配置 Homestead设置 Provider配置共享文件夹配置 Nginx 站点Hosts文件启动 Vagrant Box可
我有一个网站,包括2个不同的登录表单,2个位置,一个在导航栏上,另一个是登录页面,将在系统捕获未登记的访问者时使用.我可以问一下我在LoginRequest.php中做错了什么,如果登录过程中出现任何类型的错误,我会设置一个重定向到自定义登录页面的条件?我的代码如下:<?phpnamespaceApp
这是我用于上传多个文件的控制器代码,我从GoogleChrome上的’postman’restAPI客户端传递密钥和值.我正在从邮递员添加多个文件,但只有1个文件正在上传.publicfunctionpost_files(){$allowedExts=array("gif","jpeg","jpg","png","txt","pdf","doc
1. 只需要在 config\app.php 文件中加入 faker_locale=>'zh_CN' ,可生成部分中文数据,如nameaddress 等 2. 时间生成,当月随机时间$faker->dateTimeThisMonth()3. 随机数rand(1,5)'id'=>$faker->randomElement(['1','2','3'])
我正在尝试运行迁移(见下文)并为数据库播种,但是当我运行时phpartisanmigrate--seed我收到此错误:Migrationtablecreatedsuccessfully.Migrated:2015_06_17_100000_create_users_tableMigrated:2015_06_17_200000_create_password_resets_tableMigrated:2015_06_1
我正在尝试获取所有模型的关联数组.我有以下型号:classArticleextendsEloquent{protected$guarded=array();publicstatic$rules=array();publicfunctionauthor(){return$this->belongsTo('Author');}publicfunctionc
我有一个包含以下表和关系的数据库:租房广告1-1Carm-1型号m-1品牌如果我想要检索广告,我可以简单地使用:Advert::find(1);如果我想要汽车的细节,我可以使用:Advert::find(1)->with('Car');但是,如果我还想要模型的细节(跟随与Car的关系),语法是什么,以下不起作用:Advert:
在5.3之前的Laravel项目中,我使用脚本标记使用了Vue.js,如下所示:<scripttype="text/javascript"src="../js/vue.js"></script>然后我会创建一个特定于该页面的Vue实例,如下所示:<script>newVue({el:'#app',data:{message:&#03
我似乎不明白为什么我们需要运行一个带有phpartisan服务的Laravel应用程序而不是用Apache或nginx运行它.我知道在开发过程中,我们使用artisan来启动站点,在部署到服务器之后,您使用Web服务器来加载站点.什么是首先在工匠中运行应用程序的用途?解决方法:serve命令只是PHPBuilt-in
我已经设置了以下Laravel命令:protectedfunctionschedule(Schedule$schedule){$schedule->command('command:daily-reset')->daily();$schedule->command('command:monthly-reset')->monthly();}然后,在我的服务器上,我已经设置了一个cron作业,
所以我向reviewsController@export发了一个小的ajax请求.现在当我在console.log()成功方法中的数据时,ajax响应显示正确的数据.但是我的CSV尚未下载.所以我拥有所有正确的信息并且基本上创建了csv.我认为这可能与设置标题有关吗?publicfunctionexport(){header("Conte
我之前没有遇到过这个问题,但是我的php工匠修补程序因发出任何命令而崩溃–并且没有留下任何导致崩溃的日志.project4$phpartisantinkerPsyShellv0.9.9(PHP7.3.0—cli)byJustinHileman>>>use\App\Jobs\testJob;project4$甚至是最简单的命令:project4$php
在进行laravel迁移时,我面临一些小小的不便.我使用Laravel5.1.由于存在许多具有许多关系的表,因此我可能无法重命名迁移文件,因此它们以正确的顺序运行,因此不会违反外键约束.这就是我过去做过的事情,而且非常不实用.我现在正在做的是定义每个迁移,如下所示:classCreateSomeTa
当我运行它输出:phpartisanserve--port=80Laraveldevelopmentserverstartedonhttp://localhost:80如何让它在后台运行,当我退出控制台时服务器停止.解决方法:简短的回答:不要Web服务器工匠使用的是PHP内置Web服务器,它不适用于除了开发之外的任何场景,如Built-inwebs
我仔细阅读并重新阅读了Vuedocs“ReactivityinDepth”以及vm.$set和Vue.set的API,但我仍然很难确定何时使用哪个.我能够区分这两者是很重要的,因为在我目前的Laravel项目中,我们动态地在对象上设置了很多属性.文档中的区别似乎是vm.$set为“ForVueinstance”的语言,而Vue.se
我一直试图从上传的文件中获取扩展名,在谷歌搜索,我没有得到任何结果.该文件已存在于路径中:\Storage::get('/uploads/categories/featured_image.jpg);现在,我如何获得上述文件的扩展名?使用输入字段我可以像这样获得扩展:Input::file('thumb')->getClientOriginalExtension(
我正在尝试使用信息https://github.comrk/predis连接到具有predis1.1和SSL的Redis,其中在示例中使用以下配置://Namedarrayofconnectionparameters:$client=newPredis\Client(['scheme'=>'tls','ssl'=>['cafile'=>'p
根据Laravel4documentation.作曲家是:Viewcomposersarecallbacksorclassmethodsthatarecalledwhenaviewisrendered.Ifyouhavedatathatyouwantboundtoagivenvieweachtimethatviewisrenderedthroughoutyourapplication,aviewcomposercan
是否可以手动注册用户(与工匠?)而不是通过身份验证注册页面?我只需要一些用户帐户,并想知道是否有办法创建这些帐户而无需设置注册控制器和视图.解决方法:我想你想一次性这样做,所以不需要像创造一个Artisan命令那样花哨的东西等等.我建议简单地使用phpartisantinker(很棒的工具!)
所以我的迁移文件夹看起来像这样,因为我有几十个表,它保持组织和清洁:migrations/create_user_table.phprelations/translations/我正在尝试刷新所有迁移和种子,但似乎我遇到了轻微的打嗝,我不知道artisan命令以递归方式运行迁移(即在关系和翻译文件夹中运行迁移).我