Nor*_*gul 4 php routes laravel
我的控制器位于与 Laravel native 不同的文件夹中App\Http\Controllers
。我正在使用一个自定义Lib\MyApp
文件夹,其中包含模块。每个模块都有自己的控制器、模型等。我添加了composer.json
自动加载到app\lib
.
我所做的是更改RouteServiceProvider
命名空间:
protected $namespace = 'App\Lib\MyApp';
Run Code Online (Sandbox Code Playgroud)
我做了composer dump-autoload
一切之后。
里面MyApp
是一个Landing\Controller
文件夹,里面有实际的控制器类。
尝试 1(理想):
我想这样称呼我的路线:
Route::get('/', 'Landing\Controller\LandingController@index');
Run Code Online (Sandbox Code Playgroud)
但这样我就得到了ReflectionException
即使没有找到该类
尝试2:
Route::get('/', '\Landing\Controller\LandingController@index');
Run Code Online (Sandbox Code Playgroud)
当我刷新页面时,尾部斜杠会删除名称空间部分,并且类仍然被认为不存在。
尝试3:
Route::get('/', 'MyApp\Landing\Controller\LandingController@index');
Run Code Online (Sandbox Code Playgroud)
这只是复制MyApp
文件夹,并且未按预期找到类。
尝试4(工作,但不想要这样)
Route::get('/', '\MyApp\Landing\Controller\LandingController@index');
Run Code Online (Sandbox Code Playgroud)
虽然我想去掉这个\MyApp\
部分,但效果很好。
这样的事情可能吗?
您可以在路由中使用命名空间来实现此目的:
Route::namespace('Landing\Controller')->group(function () {
Route::get('/', 'LandingController@index');
// + other routes in the same namespace
});
Run Code Online (Sandbox Code Playgroud)
并且不要忘记将名称空间添加到控制器中:
<?php namespace App\Lib\MyApp\Landing\Controller;
Run Code Online (Sandbox Code Playgroud)
PS:如果 Lib 位于 App 文件夹内,则无需在 Composer 文件中添加任何内容,因为 App 文件夹已在 中注册,psr-4
这样它将为您加载此命名空间内的所有文件。