Answer the question
In order to leave comments, you need to log in
Laravel how to register your service?
I read this article https://laravel-news.ru/blog/tutorials/design-patt...
It describes how to use the Service Layer pattern.
It all boils down to creating the app/Services directory and in it the Service class and accessing it in the controller.
How to connect it so that it is available in the controller is not said. I tried to repeat the example from the article, I get the error Undefined property: App\Http\Controllers\HomeController::$createCouponService
As I understand it, the new service needs to be connected somehow?
Answer the question
In order to leave comments, you need to log in
Read The Following Manual .
// app/providers/AppServiceProvider.php
use App\Services\Coupon\CreateCoupon;
use App\Services\Notification;
class AppServiceProvider
{
public function register()
{
// for regular services
$this->app->bind(CreateCoupon::class);
// for singletons
$this->app->singleton(Notification::class);
}
}
// app/http/controllers/CouponController
use App\Services\Coupon\CreateCoupon;
class CouponController
{
public function create(Request $request, CreateCoupon $service)
{
$service->create($request->input());
}
}
namespace App\Services\Insurance\Ally;
use App\Contracts\InsuranceProvider;
class Provider implements InsuranceProvider
{
public function __construct()
{
// Api === App\Services\Insurance\Ally\Api, совпадает namespace
// Сервис Api нужен исключительно этому провайдеру
$this->api = new Api();
}
public function getTerms($invoice)
{
// получаем данные с api и отдаем их
return $this->api->getTerms($invoice);
}
}
namespace App\Services\FormBuilder;
// AppServiceProvider::register()
// $this->app->bind(HtmlRenderer::class);
use App\Services\Renderer\HtmlRenderer;
class Builder
{
public function __construct(HtmlRenderer $renderer)
{
$this->inputFactory = new InputFactory();
$this->renderer = $renderer;
$this->inputs = [];
}
public function addInput($type, $className, $placeholder)
{
$this->inputs[] = $this->inputFactory->create($type, $className, $placeholder);
}
public function render()
{
return $this->renderer->render($this->inputs);
}
}
use App\Contracts\Renderer;
public function register()
{
$this->app->register(Renderer::class, function ($params) {
switch ($params['type']) {
case 'html':
return new HtmlRenderer();
case 'xml':
return new XmlRenderer();
}
});
}
// some service
use App\Contracts\Renderer;
class FormBuilder
{
public function __construct($rendererType)
{
$this->renderer = app()->make(Renderer::class, ['type' => $rendererType]);
}
}
Have you entered your namespace correctly?
You should treat like thisnew App\Services\MyService()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question