【问题标题】:Route group namespace in Laravel 8Laravel 8 中的路由组命名空间
【发布时间】:2021-05-12 08:24:44
【问题描述】:

我正在尝试在 laravel 中定义命名空间

旧版

Route::group('namespace' => 'RoleA'], function() {
    Route::get('/', 'HomeController@index']);
    // call RoleA/HomeController
});

laravel 8

use App\Http\Controllers\RoleA\HomeController;
use App\Http\Controllers\RoleB\HomeController;
// return error => HomeController already in use

Route::group('namespace' => 'RoleA'], function() {
    Route::get('/', [HomeController::class, 'index']);
    // call RoleA/HomeController
});

Route::group('namespace' => 'RoleB'], function() {
    Route::get('/', [HomeController::class, 'index']);
    // still call RoleA/HomeController
});

在 Laravel 8 中是否有另一种方式或正确的方式来使用命名空间?

编辑,抱歉这个模棱两可的问题

我的意思是像旧版本一样,在定义命名空间时 类似这样,或者看上面的旧版本

Route::group('namespace' => 'RoleB'], function() {
    Route::get('/', [RoleB/HomeController::class, 'index']);
    // will call RoleB/HomeController
});

有没有办法实现类似上面的代码?

【问题讨论】:

    标签: laravel frameworks backend laravel-routing laravel-8


    【解决方案1】:

    按如下方式导入控制器 -

    
    use App\Http\Controllers\Admin\TestController as TestControllerAdmin;
    use App\Http\Controllers\Employee\TestController as TestControllerEmployee;
    
    Route::group(["prefix"=>"admin"], function(){
        Route::get('index',  [TestControllerAdmin::class, 'index']);
    });
    Route::group(["prefix"=>"employee"], function(){
        Route::get('index',  [TestControllerEmployee::class, 'index']);
    });
    

    【讨论】:

      【解决方案2】:

      我认为 laravel 放弃了这个功能,因为在 laravel 8 中,控制器将是面向对象的类

      Laravel 路由 7.* 文档。

      Laravel 路由 8.* 文档。

      【讨论】:

      • 您可以在文档中看到“在适当的地方自动添加 URI 前缀中的命名空间分隔符和斜杠”laravel.com/docs/8.x/routing
      • @Mtkz 你能用例子详细说明一下吗?我可以清楚地理解意思
      【解决方案3】:

      对于返回错误,请按如下方式导入控制器(您不能导入同名类。因此您应该为名称起别名)

      use App\Http\Controllers\RoleA\HomeController as HomeControllerA;
      use App\Http\Controllers\RoleB\HomeController as HomeControllerB;
      

      然后您可以将路由组创建为this

      Route::prefix('RoleA')->group(function () {
          Route::get('/', function () {
              // Matches The "/RoleA" URL
          });
      });
      

      你可以使用如下命名空间

      Route::group(['namespace' => 'HomeControllerA'], function()
      {
          Route::get('/RoleA', [HomeController::class, 'index']);
      }
      

      【讨论】:

      • 命名空间怎么样,Laravel 8 中有没有使用命名空间的方法,还是现在不需要?
      猜你喜欢
      • 2018-05-05
      • 2021-01-10
      • 2015-10-26
      • 1970-01-01
      • 2017-12-13
      • 2015-07-05
      • 2019-05-03
      • 2015-09-23
      相关资源
      最近更新 更多