laravel - DI, класс не найден - PullRequest
       0

laravel - DI, класс не найден

0 голосов
/ 26 сентября 2018

Я создал сервис для своего приложения:
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 голосов
/ 26 сентября 2018

Вам необходимо объявить об этом в ServiceContainer в Laravel

Шаг 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,
]
...