欢迎来到代码驿站!

PHP代码

当前位置:首页 > 软件编程 > PHP代码

laravel实现前后台路由分离的方法

时间:2021-05-26 08:12:55|栏目:PHP代码|点击:

当我们把路由写到一个文件中时,路由显得杂乱不堪,不利于维护,这时我们需要将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了。

上一篇:PHP和javascript常用正则表达式及用法实例

栏    目:PHP代码

下一篇:php数组对百万数据进行排除重复数据的实现代码

本文标题:laravel实现前后台路由分离的方法

本文地址:http://www.codeinn.net/misctech/128978.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有