Laravel 5: 如何将管理控制器放在文件夹中?

Laravel 5: how to put admin controllers in a folder?

我正在 Laravel 5 创建我的第一个管理面板。我想像这样组织我的控制器:

Http
    Controllers
        Admin
            DashboardController.php
        Controller.php
        WelcomeController.php

但是我在使用它时遇到了一些问题。

DashboardController.php 是:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class DashboardController extends Controller {

    public function index()
    {
        return \View::make('admin/dashboard');
    }
}

?>

我的路线包含:

Route::group(array('namespace'=>'Admin'), function()
{
    Route::get('/dashboard', array('as' => 'dashboard', 'uses' => 'DashboardController@index'));
});

// Eventually I will check for authentication using:
// Route::group(array('before' => 'auth', 'namespace'=>'Admin'), function()...

当我导航到 /dashboard 时,我得到的错误是:

Class App\Http\Controllers\Admin\DashboardController does not exist

有什么建议吗?谢谢!

尝试在命名空间中使用文件夹名称的代码,您必须使用文件夹作为命名空间,即它遵循文件夹名称作为命名空间 App/Http/Controller/Admin

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

class DashboardController extends Controller {

    public function index()
    {
        return \View::make('admin/dashboard');
    }
}

?>

路由保持原样

Route::group(array('namespace'=>'Admin'), function()
{
    Route::get('/dashboard', array('as' => 'dashboard', 'uses' => 'DashboardController@index'));
});

Laravel 5 比之前版本的 Laravel.

更严格地遵守命名空间标准

这意味着更改文件夹结构也会更改自动加载器查找 class 的命名空间。

在本例中,您已将命名空间 Admin 添加到 DashboardController。

您的声明 namespace App\Http\Controllers; 应更改为

namespace App\Http\Controllers\Admin;

同样,如果您对文件夹结构进行进一步更改,例如在 Admin 下为 SuperAdmin 添加新的子文件夹,您需要将该命名空间添加到 classes在该文件夹中。这也适用于其他文件夹,例如您的 HandlersEvents

如果您开始更改文件夹结构,最好了解 PHP 的命名空间概念。这里有一个快速学习的好教程:http://daylerees.com/php-namespaces-explained

有一种误解认为 Laravel 5 现在强制使用特殊的文件夹结构。

但是不,它没有

你的代码的问题是:

Route::group(array('namespace'=>'Admin'), function()
{
    Route::get('/dashboard', 
    array('as' => 'dashboard', 'uses' => 'DashboardController@index'));
});

您正在使用命名空间 Admin,而在您的控制器中,没有这样的命名空间。因此,laravel 会抱怨。

如果删除此 array('namespace=>'Admin'),您的代码将 运行 正常。

但是如果你想保留命名空间,那么有一个方法,

<?php

namespace App\Http\Controllers\Admin; \Add the admin part.

use App\Http\Controllers\Controller;

class DashboardController extends Controller {

    public function index()
    {
        return \View::make('admin/dashboard');
    }
}

?>

现在可以访问了。

注#1: 但这并不意味着 DashboardController 必须驻留在 admin 文件夹中

事实上,它可以放在任何文件夹中。 只要你保持正确的命名空间它就和以前的版本一样。您需要做的就是 运行 一个

composer dump-autoload -o
or
php composer.phar dump-autoload -o

composer 将自动加载文件。