Answer the question
In order to leave comments, you need to log in
How to access base in DependencyInjection?
Please do not kick much, I'm still a teapot.
There was a task to load some user settings from the database. The admin writes these settings in the Sonata Admin section, and my task is to pull them out and use them in different places. And something seemed to me not very convenient to pull this data every time. I decided to try to load these settings into the service container in DependencyInjection.
Two questions arose:
1. Does such an approach have the right to life?
2. How to access the database from DependencyInjection?
Answer the question
In order to leave comments, you need to log in
Pass in the EntityManager constructor
Example:
class MyPropertyService{
private $property1;
// ....
public function __construct(EntityManager $em){
// ваш код инициализации
// $this->property1 = ...
}
//...
}
<service id="my.property.service" class="Acme\SuperBundle\Services\MyPropertyService">
<argument type="service" id="doctrine.orm.default_entity_manager"/>
</service>
Where will MyPropertyService be called from? From DependencyInjection call it?
Create a simple service:
use Doctirne\ORM\EntityManager;
class SettingLoader
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function get($key)
{
$val = $this->em->getRepository('MailBundle:Setting')->findOneBy(array('key' => $key));
if (!$val) { throw new \InvalidArgumentException('Setting not found.'); }
return $val;
}
}
<service id="settings_loader" class="MyBundle\SettingLoader">
<argument type="service" id="doctrine.orm.default_entity_manager" />
</service>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question