Laravel optimization split routing file

*文
Release: 2023-03-18 22:02:02
Original
2432 people have browsed it

本文是一篇关于Laravel分割路由文件(routes.php)的最佳方式教程文章,内容介绍的很详细,学习Laravel的小伙伴可以参考学习。

前言

Laravel 的路由功能很强大,默认都是定义在routes.php文件中,随着项目越来越大,我们需要的定义的路由越来越多,想象一下,如果几百上千个路由都定义在一个文件中,如何去维护?也许还有不同的人都在同一个文件定义路由,这就造成了冲突,因此我们需要分割routes.php文件。

下面介绍一种很优雅的方式。

app/Providers/RouteServiceProvider.phpmap方法中可以如下定义:

public function map(Router $router) { $router->group(['namespace' => $this->namespace], function ($router) { //require app_path('Http/routes.php'); foreach (glob(app_path('Http//Routes') . '/*.php') as $file) { $this->app->make('App\\Http\\Routes\\' . basename($file, '.php'))->map($router); } }); }
Copy after login

文件组织结构图如下:

这样它会遍历app/Http/Routes/文件夹下的文件,遍历每个文件路由类的map方法,每个文件的结构都类似,

举个例子:

group(['domain' => 'www.tanteng.me', 'middleware' => 'web'], function ($router) { $router->auth(); $router->get('/', ['as' => 'home', 'uses' => 'IndexController@index']); $router->get('/blog', ['as' => 'index.blog', 'uses' => 'BlogController@index']); $router->get('/resume', ['as' => 'index.resume', 'uses' => 'IndexController@resume']); $router->get('/post', ['name' => 'post.show', 'uses' => 'ArticleController@show']); $router->get('/contact', ['as' => 'index.contact', 'uses' => 'IndexController@contact']); $router->post('/contact/comment', ['uses' => 'IndexController@postComment']); $router->get('/travel', ['as' => 'index.travel', 'uses' => 'TravelController@index']); $router->get('/travel/latest', ['as' => 'travel.latest', 'uses' => 'TravelController@latest']); $router->get('/travel/{destination}/list', ['as' => 'travel.destination', 'uses' => 'TravelController@travelList']); $router->get('/travel/{slug}', ['uses' => 'TravelController@travelDetail']); $router->get('/sitemap.xml', ['as' => 'index.sitemap', 'uses' => 'IndexController@sitemap']); }); } }
Copy after login

把路由规则都写到每个文件的map方法中,这样一来,就实现了很好的routes.php文件的分开管理。此外,你也可以简单的分割,直接把routes.php中的定义拆散成多个文件,通过require的方式引入,但是哪个更好,一目了然。

那么这样路由分开多个文件后岂不是增加调用次数,会不会影响性能?答案是不必担心。通过Laravel的命令:

php artisan route:cache
Copy after login

生成路由缓存文件后,路由只会读取缓存文件的路由规则,因此不会影响性能,这样做让开发更高效和规范。

相关推荐:

利用Laravel生成Gravatar头像地址的优雅方法

Laravel使用Pagination插件实现自定义分页

laravel编写APP接口(API)

The above is the detailed content of Laravel optimization split routing file. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!