1

Laravel多路由文件配置

 2 years ago
source link: https://caihongtengxu.github.io/2019/20191210/index.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Laravel多路由文件配置

发表于 2019-12-10

  |   分类于 PHP

  |   0 Comments

写了个把月前端后,重新接手了一个后台老项目(Lumenl5.2的),然后发现路由配置文件写了3000多行,想加点东西是真累啊!为什么就都不知道改造下?分成多个配置文件不香么,非要使劲在一个里面添加!


Lumen5.2下多路由文件配置

这个用的版本太老了最新版的6.0暂时还没看。

先说下如果想分成多个路由配置文件的解决办法!

在默认情况下,Lumen下的路由配置都是读取的 app/Http/routes.php 文件,可以修改项目根目录下的 bootstrap/app.php 文件。

打开看下:

|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
require __DIR__ . '/../app/Http/routes.php';

根据官方的注释路由文件是通过这里引入的,那么就好办了。 直接在项目根目录下新建一个 routes 文件夹,然后以后新的路由配置文件都放在这里统一管理。比如我就新加了一个 recruit_setting.php 路由文件。

然后修改上面的代码添加进去即可。

$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
require __DIR__ . '/../app/Http/routes.php';
require __DIR__ . '/../routes/recruit_setting.php';

Laravel5.5以上版本多路由文件配置

如果是Laravel5.5以上的版本就简单多了,官方给出了优雅的解决方案。默认所有的路由配置文件都是放在项目跟目录下的 routes 文件夹内。然后在 app/Providers/RouteServiceProvider.php 文件内进行路由服务配置。

打开上面这个文件 主要看下 map() 方法

* Define the routes for the application.
* @return void
public function map()
$this->mapApiRoutes();
$this->mapWebRoutes();

这里默认添加了2个路由配置,一个是通用访问的web路由配置,一个是api访问的配置。

随便看下 mapApiRoutes() 方法

* Define the "api" routes for the application.
* These routes are typically stateless.
* @return void
protected function mapApiRoutes()
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));

可以看出他这里引入了 routes/api.php 文件,也就是对应的配置文件。这就好办了,如果以后要增加自己的路由配置文件,只需要模仿他即可。比如我现在要加一个文件处理的路由配置文件,可以这样操作。

1.先定义相关路由方法

* 文件操作相关路由
* @return void
public function mapFileRoutes()
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/file.php'));

前面设置的路由 prefix('api')middleware('api')namespace('xxx') 是些通用的路由前缀、中间件、命名空间的设置,可以根据自己的需求进行删除或者替换。

2.在 map() 方法中调用自己新增加的路由定义方法

public function map()
$this->mapApiRoutes();
$this->mapWebRoutes();
// 自定义文件操作相关路由
$this->mapFileRoutes();

3.在 routes 文件夹下增加 file.php 路由配置文件。这里就是常规路由的配置了

/*文件相关操作路由配置*/
Route::group(['prefix' => 'v1', 'namespace' => 'V1'], function($app) {
$app->group(['prefix' => 'file'], function ($app) {
$app->get('test', 'FileController@test')->middleware('oauth:user');
-------------The End-------------
PHP

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK