向Laravel 5包添加控制器


Add a Controller to a Laravel 5 Package

最近,我一直在为我的L5包创建模型,但现在我想尝试并引入一个控制器。我一直遵循这个,但我总是得到错误"Class StatController does not exist" .

文件夹结构

/src
    routes.php
    /Controllers
        StatController.php

StatController.php

<?php namespace Enchance'Sentrysetup'Controllers;
use App'Http'Controllers'Controller;
class StatController extends Controller {
    public function index() {
        return 'Moot.';
    }
}
服务提供者

public function register()
{
    // Can't get this to work
    include __DIR__.'/routes.php';
    $this->app->make('Enchance'Sentrysetup'Controllers'StatController');
    $this->app['sentrysetup'] = $this->app->share(function($app) {
        return new Sentrysetup;
    });
}

routes.php

Route::get('slap', 'StatController@index');

是否有人有另一种方法将控制器分配给L5包?

您不需要在控制器上调用$this->app->make()。控制器由Laravel的IoC自动解析(这意味着Laravel会自动创建/实例化绑定到路由的控制器)。

要求您的路由在您的包服务提供商的boot()方法中:

public function boot()
{
    require __DIR__.'/routes.php';     
}

在你的routes.php文件中:

Route::group(['namespace' => 'Enchance'Sentrysetup'Controllers'], function()
{
    Route::get('slap', ['uses' => 'StatController@index']);
})

还有,这只是一个提示。您应该PascalCase您的名称空间:

Enchance'SentrySetup'Controllers

注意setup

中的大写S

应该使用boot()方法来注册路由,因为当Laravel启动时,它会遍历config/app.php文件中的每个服务提供商,创建它们,调用register()方法(插入/添加服务提供商提供的任何依赖项)。

把Laravel的容器想象成一个简单的大key =>值数组。其中"键"在哪里?是依赖项的名称(例如config),以及"值"。是一个闭包(function () {}),用于创建依赖项:

// Exists as a property inside the Container:
$bindings = [
    "config" => function () {
        // Create the application configuration.
    }
];
// Create the app configuration.
$config = $bindings['config']();
// Create the app configuration (Laravel).
$config = app()->make('config');

一旦Laravel注册了每个提供者,它就会再次遍历它们并调用boot()方法。这确保了任何已注册的依赖项(在所有应用程序服务提供者的register()方法中)在boot()方法中可用,可以随时使用。

The Service Provider Boot Method - Laravel Docs

在控制器函数中使用:

use Illuminate'Routing'Controller;

:

namespace Enchance'Sentrysetup'Controllers;
use Illuminate'Routing'Controller;
class StatController extends Controller {
    public function index() {
        return 'Moot.';
    }
}

And in controller:

Route::group(['namespace' => 'Enchance'Sentrysetup'Controllers'], function()
{
    Route::get('slap', 'StatController@index');
});

In boot function:

public function boot()
{
    require __DIR__.'/routes.php';     
}