Answer the question
In order to leave comments, you need to log in
How to make a shared service in all controllers?
In general, I have a Settings service, in which methods for getting site settings.
I need it in every controller, because it is used in 99% of controllers. I decided to just make a method in the parent controller:
public function settingService()
{
return $this->get('app.setting');
}
abstract class Controller extends AbstractController
{
public $settingService;
public function __construct(Setting $settingService)
{
$this->settingService = $settingService;
}
}
Answer the question
In order to leave comments, you need to log in
The abstract controller implements the Service Subscriber . You just need to add your Setting there:
abstract class Controller extends AbstractController
{
public static function getSubscribedServices()
{
return array_merge(parent::getSubscribedServices(), [
'setting' => Setting::class,
]);
}
protected function getSetting(): Setting
{
return $this->get('setting');
}
}
The simplest option is to write your own compiler pass , select services in it (via findTaggedServiceIds
) by tag controller.service_arguments
and complete the definition of services either by calling your method or adding an argument to the constructor, this can be done by name.
You can make an even more general solution: define an interface, for example SettingsAwareInterface
something like this:
namespace App\Contracts;
interface SettingsAwareInterface
{
public function getSettings(): Setting;
public function setSettings(Setting $settings): void;
}
services.yaml
add:_instanceof:
App\Contracts\SettingsAwareInterface:
tags:
- {name: 'app.settings-aware'}
app.settings-aware
, this will allow you to pass this service not only to controllers.
will use __construct, then I will need to duplicate all constructor arguments
You can use the annotation@required
/**
* @required
*/
public function setSetting(Setting $setting)
{
$this->setting = $setting;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question