I'm have created service for my application:
ProductsShelfService
<?php
declare(strict_types=1);
namespace App\Modules\ProductList\Services;
class ProductsShelfService
{
public function sample()
{
return 'I am ProductsShelfService class!';
}
}
and now I want to pass it to controller via 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();
}
}
but I getting error:
ReflectionException
Class App\Modules\ProductList\Services\ProductsShelfService does not exist
Why? I need to do sth more?
You need to declare it to ServiceContainer in Laravel
Step 1: create a ProductsShelfProvider
php artisan make:provider ProductsShelfProvider
Step 2: register your service in 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();
});
}
}
Step 3: declare in config/app
'providers' => [
...
Illuminate\View\ProductsShelfProvider::class,
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.