问题描述
在Laravel5中路由似乎对我来说是一个主要问题.
Routing in Laravel5 seems to be a major problem for me.
我希望使用作曲家映射来遵循这个示例
I was hoping to follow this example using the composer mapping
https://mattstauffer.co/Blog/upgradeing-from-laravel-4-to-laravel-5#namespacing-controllers
为避免模型或立面出现任何问题.
To avoid any issues with models or facades.
但是当我路由到此时:
Route::get('school/test', 'school\SchoolController@index');
错误
ReflectionException in Container.php line 776: Class school\SchoolController does not exist
SchoolController位于HTTP/controllers/school文件夹中:
The SchoolController is in the HTTP/controllers/school folder:
namespace School
class SchoolController extends Controller{
public function index() {
return "hello";
}
}
RouteServiceProvider:
RouteServiceProvider:
protected $namespace=NULL
为HTTP/控制器设置了
composer
composer is set for the HTTP/controllers
"classmap": [
"database",
"app/Models",
"app/HTTP/Controllers"
]
和适用于这样的路线:
Route::resource('courses', 'CourseController');
因此,路由器只是不在子文件夹中找到文件.我想知道是什么问题?
似乎唯一的选择是
RouteServiceProvider
protected $namespace = 'App\Http\Controllers';
Composer.json
Composer.json
`"classmap": [
"database",
"app/Models"
],
App \ Http \ Controllers中的HomeController;
HomeController in the App\Http\Controllers;
namespace App\Http\Controllers;
use App\Models\Course;
class HomeController extends Controller {
public function index()
{
$courses =Course::orderBy('created_at','DESC')->with('school')->paginate(12);
}
但这意味着我需要为100多个不同型号的控制器文件添加"use App/..."!
到目前为止,我非常感谢您的帮助,但是我真的在寻找一种可能的方法,因为第二种方法涉及将所有模型图放置在每个控制器中(很多代码).除非有一种全局方法将所有模型映射到一个文件中?
I appreciate help so far but I'm really looking for method one if possible, as two will involve placing all the model maps in each controller (lots of code). Unless there is a global way to map all the models in one file?
有人建议使用Alias,但这不起作用.
Someone suggested Alias but this doesn't work.
再次重申该问题. 使用composer进行映射的Controllers子文件夹的路由失败
推荐答案
默认情况下,Laravel将在App\Http\Controllers
中搜索控制器.您可以通过编辑App\Providers\RouteServiceProvider
:
Laravel will by default search for controllers in App\Http\Controllers
. You can change that namespace by editing App\Providers\RouteServiceProvider
:
protected $namespace = 'App\Http\Controllers';
在您的情况下,由于您根本不需要基本名称空间",请将其设置为null
:
In your case, since you want no "base namespace" at all, set it to null
:
protected $namespace = null;
- 创建的目录结构:
app/Controllers/Folder
(名称与其他名称匹配并不重要) - 在
Folder
中创建的控制器:TestController.php
(namespace Folder;
) - 在
composer.json
中编辑autoload > classmap
并添加"app/Controllers"
- 运行
composer dump-autoload
- Created directory structure:
app/Controllers/Folder
(the names don't really matter as long as they match with the rest) - Created controller in
Folder
:TestController.php
(namespace Folder;
) - Edited
autoload > classmap
incomposer.json
and added"app/Controllers"
- Run
composer dump-autoload
这篇关于Laravel 5中的路由错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!