A
A
Andrey Godin2013-04-29 19:45:27
symfony
Andrey Godin, 2013-04-29 19:45:27

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

3 answer(s)
J
JekaRu, 2013-04-29
@JekaRu

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>

A
Andrey Godin, 2013-04-29
@xilix

Where will MyPropertyService be called from? From DependencyInjection call it?

V
Vitaly Zhuk, 2013-06-07
@ZhukV

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;
  }
}

And finally, the service itself:
<service id="settings_loader" class="MyBundle\SettingLoader">
  <argument type="service" id="doctrine.orm.default_entity_manager" />
</service>

Key for default manager: doctrine.orm.default_entity_manager

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question