簡體   English   中英

將控制器添加到 Laravel 5 包

[英]Add a Controller to a Laravel 5 Package

最近,我一直只為我的 L5 包創建模型,但現在我也想嘗試引入一個控制器。 我一直在關注這個,但我總是收到錯誤"Class StatController does not exist"

文件夾結構

/src
    routes.php
    /Controllers
        StatController.php

狀態控制器.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;
    });
}

路由文件

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

注意設置中的大寫 S

boot()方法應該用於注冊你的路由,因為當 Laravel 啟動時,它會通過你的config/app.php文件中的每個服務提供者,創建它們,調用register()方法(插入/添加任何依賴服務提供者“提供”到 Laravel 的單例/IoC 容器中)。

將 Laravel 的容器視為一個簡單的大鍵 => 值數組。 其中“鍵”是依賴項的名稱(例如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()方法中可用,隨時可用。

服務提供者啟動方法 - Laravel Docs

在控制器功能中使用它:

use Illuminate\Routing\Controller;

喜歡:

namespace Enchance\Sentrysetup\Controllers;

use Illuminate\Routing\Controller;

class StatController extends Controller {

    public function index() {
        return 'Moot.';
    }

}

在控制器中:

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

在啟動功能中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM