laravel-DI,找不到类

时间:2018-09-26 07:21:56

标签: php laravel-5 dependency-injection

我已经为我的应用创建了服务:
ProductsShelfService

<?php
declare(strict_types=1);
namespace App\Modules\ProductList\Services;

class ProductsShelfService
{
    public function sample()
    {
        return 'I am ProductsShelfService class!';
    }
}

现在我想通过DI将其传递给控制器​​:
ProductListController

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Website\Pages;

use App\Http\Controllers\Controller;
use App\Modules\ProductList\Services\ProductsShelfService;

class ProductListController extends Controller
{
    /**
     * @var ProductsShelfService
     */
    protected $shelfService;

    public function __construct(ProductsShelfService $shelfService)
    {
        $this->shelfService = $shelfService;
    }

    public function index()
    {
        echo $this->shelfService->sample();
    }
}

但我收到错误消息:

ReflectionException
Class App\Modules\ProductList\Services\ProductsShelfService does not exist

为什么?我还需要做些什么?

1 个答案:

答案 0 :(得分:0)

您需要在Laravel中将其声明给ServiceContainer

第1步:创建一个ProductsShelfProvider

php artisan make:provider ProductsShelfProvider

第2步:在ProductsShelfProvider中注册您的服务

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Modules\ProductList\Services\ProductsShelfService;

class ProductsShelfProvider extends ServiceProvider
{
    public function boot()
    {

    }

    public function register()
    {
         $this->app->bind('App\Modules\ProductList\Services\ProductsShelfService', function ($app) {
            return new ProductsShelfProvider();
        });
    }
}

第3步:在config / app中声明

'providers' => [
    ...
    Illuminate\View\ProductsShelfProvider::class,
]