当前位置: 首页 > 后端技术 > PHP

源码解读:Laravelphpartisanroute-cache

时间:2023-03-29 20:49:40 PHP

学习Laravel和Vuejs,真的要来codecasts.com!Laravelroute:cache可以直接缓存路由文件,这样其实可以在一定程度上提升Laravel应用的性能,因为缓存了路由之后,我们在访问应用时不需要再计算路由消耗,直接执行即可基于缓存文件的匹配处理。不过本文的重点还是route:cache背后的源码,这一步是如何实现的。从哪里开始看route:cache源码位于Illuminate\Foundation\Console\RouteCacheCommand。还是可以用编辑器搜索RouteCacheCommand,可以看到源码。主要代码逻辑在fire()方法中:publicfunctionfire(){$this->call('route:clear');//....其他代码}第一步是执行$this->call('route:clear'),这部分的逻辑是:如果之前有缓存的路由文件,则清除旧的路由缓存首先,这部分的代码位于Illuminate\Foundation\Console\RouteClearCommand,还是看fire()方法这里:publicfunctionfire(){$this->files->delete($this->laravel->getCachedRoutesPath());$this->info('路由缓存已清除!');}主要是执行删除动作,删除之前缓存的路由;此源代码位于Illuminate\Foundation\Application的getCachedRoutesPath()中:publicfunctiongetCachedRoutesPath(){return$this->bootstrapPath().'/cache/routes.php';所以这个看,bootstrap/cache/routes.php文件被删除了,那么这个文件其实就是Laravel的路由缓存文件,后面会重新生成routes.php文件。第二步,获取所有路由及其对应关系,在RouteCacheCommand的fire()方法中往下走:publicfunctionfire(){//...codes$routes=$this->getFreshApplicationRoutes();//...codes}getFreshApplicationRoutes()的代码是:->refreshNameLookups();$routes->refreshActionLookups();});}这里还包含了一个新的方法getFreshApplication(),它也位于同一个文件中:$app){$app->make(ConsoleKernelContract::class)->bootstrap();});}这样看,总结一下这两个方法做了什么事情就是:getFreshApplication()得到一个Laravel的核心实例,然后在上面的getFreshApplicationRoutes中$this->getFreshApplication()['router']->getRoutes()()可以理解,相当于app('router')->getRoutes(),这个getRoutes()是负责获取所有路由,这部分源码位于Illuminate\Routing\Router的getRoutes()中。第三步,序列化所有路由注册映射关系,或者在RouteCacheCommand的fire()方法中:}}上面的prepareForSerialization()方法位于Illuminate\Routing\Route中的prepareForSerialization()。第四步序列化完成后,将内容写入文件。这个文件就是一开始删除的bootstrap/cache/routes.php。看代码RouteCacheCommand的fire()方法:$this->files->put($this->laravel->getCachedRoutesPath(),$this->buildRouteCacheFile($routes));其中$this->laravel->getCachedRoutesPath()是文章开头解释的,它找到了bootstrap/cache/routes.php这个文件,然后写入内容为:protectedfunctionbuildRouteCacheFile(RouteCollection$routes){$stub=$this->files->get(__DIR__.'/stubs/routes.stub');返回str_replace('{{routes}}',base64_encode(serialize($routes)),$stub);在这个方法中,看到base64_encode(serialize($routes))这一行,所以你会在缓存的routes.php中看到类似下面的代码:app('router')->setRoutes(unserialize(base64_decode('TzozNDoiSWxs??dW1pbm...')));一堆base64字符串,这些字符串base64_decode()出来是这样的:这里是完整的注册路径!那么下次访问Laravel项目时,就可以直接从缓存的路由文件中读取路由了。至此,route:cache的源码解读就完成了。快乐黑客