laravel实现前后台路由分离的方法
发布:smiling 来源: PHP粉丝网 添加日期:2022-01-02 12:26:57 浏览: 评论:0
今天小编就为大家分享一篇laravel实现前后台路由分离的方法,具有很好的参考价值,希望对大家有所帮助,一起跟随小编过来看看吧。
当我们把路由写到一个文件中时,路由显得杂乱不堪,不利于维护,这时我们需要将laravel路由进行分离
实现步骤:
1、首先在app/Https/Controlles/文件下建立 Frontend(前端) Backend(后端) API(接口) 文件
2、在app/Https/建立对应的路由文件
3、打开app/Providers/RouteServiceProvider.php 定义各个功能对应的路由文件
代码如下:
- <?php
- namespace App\Providers;
- use Illuminate\Routing\Router;
- use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
- class RouteServiceProvider extends ServiceProvider
- {
- /**
- * This namespace is applied to the controller routes in your routes file.
- *
- * In addition, it is set as the URL generator's root namespace.
- *
- * @var string
- */
- protected $namespace = 'App\Http\Controllers';
- protected $backendNamespace;
- protected $frontendNamespace;
- protected $apiNamespace;
- protected $currentDomain;
- /**
- * Define your route model bindings, pattern filters, etc.
- *
- * @param \Illuminate\Routing\Router $router
- * @return void
- */
- public function boot(Router $router)
- {
- //
- $this->backendNamespace = 'App\Http\Controllers\Backend';
- $this->frontendNamespace = 'App\Http\Controllers\Frontend';
- $this->apiNamespace = 'App\Http\Controllers\API';
- // $this->currentDomain = $this->app->request->server->get('HTTP_HOST');
- $this->currentDomain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : "";
- parent::boot($router);
- }
- /**
- * Define the routes for the application.
- *
- * @param \Illuminate\Routing\Router $router
- * @return void
- */
- public function map(Router $router)
- {
- // $router->group(['namespace' => $this->namespace], function ($router) {
- // require app_path('Http/routes.php');
- // });
- $backendUrl = config('route.backend_url');
- $frontendUrl = config('route.frontend_url');
- $apiUrl = config('route.api_url');
- switch ($this->currentDomain) {
- case $apiUrl:
- // API路由
- $router->group([
- 'domain' => $apiUrl,
- 'namespace' => $this->apiNamespace],
- function ($router) {
- require app_path('Http/routes-api.php');
- }
- );
- break;
- case $backendUrl:
- // 后端路由
- $router->group([
- 'domain' => $backendUrl,
- 'namespace' => $this->backendNamespace],
- function ($router) {
- require app_path('Http/routes-backend.php');
- }
- );
- break;
- default:
- // 前端路由
- $router->group([
- 'domain' => $frontendUrl,
- 'namespace' => $this->frontendNamespace],
- function ($router) {
- require app_path('Http/routes-frontend.php');
- }
- );
- break;
- }
- }
- }
此时只需要在不同的控制器中建立路由就 Ok了。
Tags: laravel前后台路由分离
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)