How can I access a service outside of a controller with Symfony2? - symfony

I'm building a site that relies quite heavily on a third party API so I thought it would make sense to package up the API wrapper as a service, however I'm starting to find instances where it would be useful to have access to it outside of a controller such as in an entity repository.
Also related to that is it would be useful to be able to get access to config values outside of a controller (again such as in an entity repository).
Can anyone tell me if this is possible and if not is there a suggested approach to doing this kind of thing?
thanks for any help

The Symfony distribution relies heavily on dependency injection. This means that usually, dependencies are injected directly into your object via the constructor, the setters or via other means (like reflection over properties). Your API wrapper service is then a dependency for other objects of your application.
That being said, it would be rather difficult to inject this service in an entity repository's constructor because it already requires some other parameters and I think it would not be possible to inject them because of the way we request the repository for an entity.
What you could do is to create another service which will be responsible of doing the work you were about to do in the entity repository. This way, you will be able to inject the entity manager, which will be used to retrieve the entity repository, you custom service and also another service holding your configuration values (There are other ways to share configuration values).
In my use case, I use a Facebook helper service that wraps Facebook API calls. This service is then injected where I need it. My entity repository is only responsible of doing database calls so it receives only the arguments it needs and not the whole dependency. Thus, it will not receive the helper but rather only the arguments needed to do a request, for example, a Facebook user id. In my opinion, this is the way to do it since I think the entity repository should not have dependencies on such helper objects.
Here a small example using YAML as the configuration:
# app/config/config.yml
services:
yourapp.configuration_container:
class: Application/AcmeBundle/Common/ConfigurationContainer
# You could inject configurations here
yourapp.api_wrapper:
class: Application/AcmeBundle/Service/ApiWrapperService
# Inject other arguments if needed and update constructor in consequence
yourapp.data_access:
class: Application/AcmeBundle/Data/Access/DatabaseAccessService
arguments:
entityManager: "#doctrine.orm.entity_manager"
apiWrapperService: "#yourapp.api_wrapper"
configuration: "#yourapp.configuration_container"
# Application/AcmeBundle/Common/ConfigurationContainer.php
public ConfigurationContainer
{
public function __construct()
{
// Initialize your configuration values or inject them in the constructor
}
}
# Application/AcmeBundle/Service/ApiWrapperService.php
public ApiWrapperService
{
public function __construct()
{
// Do some stuff
}
}
# Application/AcmeBundle/Data/Access/DatabaseAccessService.php
public DatabaseAccessService
{
public function __construct(EntityManager $entityManager, ApiWrapperService $apiWrapperService, ConfigurationContainer $configuration)
{
...
}
}
The at sign (#) in the config.yml file means that Symfony should inject another service ,having the id defined after the at sign, and not a simple string. For the configuration values, as I said previously, there is other means to achieve the same goal like using parameters or a bundle extension. With a bundle extension, you could define the configuration values directly into the config.yml and your bundle would read them.
In conclusion, this should give you the general idea of injecting services. Here a small list of documentation on the subject. Alot of links use the XML service definition instead of the YAML definition but you should be able to understand them quite easily.
Symfony Official DI
Fabien Potencier's articles on DI
Richard Miller's articles on DI (Check in his blog for the other DI articles)
Take note that the configuration I'm giving is working for Beta1 of Symfony2. I didn't update yet to Beta2 so there could be some stuff not working as they are in the Beta2 version.
I hope this will help you defining a final solution to your problem. Don't hesitate to ask other questions if you want clarifications or anything else.
Regards,
Matt

I would wrap this kind of behavior in a Symfony service(like a manager).
i would not inject any parameters or logic into the entity repositories, as they should mainly be used to fetch data using object manager queries.
I would put the logic in the services and if the service , require a database access it will call the entity repository to fetch data.

Related

Symfony - Database connection with a Repository

I'm refactoring the code in one of my Controller to put it in a service.
In the Controller the entity manager is targeting a db connection called legacy.
The problem is, I did not injected the Entity Manager in my service but just the OrderRepository.
How can I target the good db connection with the repository in my service without the Entity Manager?
OrderController
// In my Controller
$em = $this->getDoctrine()->getManager('legacy');
$em->persist($order);
$em->flush();
OrderService
// In my Service
public function __construct(OrderRepository $orderRepository)
{
$this->orderRepository = $orderRepository;
}
public function updateOrderStatus(Order $order)
{
// some code ...
$this->orderRepository->save($order);
}
Based on some comments it would appear that the basic issue is having multiple entity managers. Nowadays there is a great deal of automated functionality which works well for one entity manager but no so much for multiple managers.
You basically need to define your services manually.
# services.yaml
# assume we have
# doctrine.orm.default_entity_manager and
# doctrine.orm.legacy_entity_manager
# already defined through configuration
# define legacy repository
order_repository.legacy:
class: Whatever\Repository\OrderRepository
factory: ['doctrine.orm.legacy_entity_manager', 'getRepository']
arguments:
- 'Whatever\Entity\Order'
# define default repository
order_repository.default:
class: Whatever\Repository\OrderRepository
factory: ['doctrine.orm.default_entity_manager', 'getRepository']
arguments:
- 'Whatever\Entity\Order'
# then your service
Whatever\Service\MyService:
'#order_repository.legacy'
And you should be good to go. Note that your repository needs to extend EntityRepository and not the doctrine bundle's ServiceEntityRepository.
And if you feel this is too much work then just inject the doctrine bundle's entity manager registry and do what the ControllerTrait::getDoctrine($name) does.
You must forgot that you can always get the entity manager inside your repository just like this:
$em = $this->getEntityManager();
then you can use it normally calling persist, flush etc.
Note that the Repository class itself is agnostic to functionalities of the database access layer like insert or update so it should call entity manager to execute them.

Symfony2 Dependency Injection the "Right Way"

This is a fairly open question, i'm looking for opinion more than anything...
Coming from Laravel, Dependency Injection (DI) was blissful, if you wanted to access a method from a class, you could either inject it by type hinting in the method or constructor and you'll have instant access to it; symfony2 doesn't seem this simple from the face of it.
We've got service containers, setter injection, constructor injection by setting up a service yml where you pre-define your arguments, but this just seems dirty.
So the "Laravel Way" of dependency injection is done like this
class Listener
{
protected $mailer;
public function __construct(Mailer $mailer)
{
$this->mailer = $mailer;
}
public function userWasAdded(User $user)
{
// Do some stuff...
$this->mailer->send('emails.welcome', ['user' => $user], function($message)
{
$message->to($user->email, $user->name)->subject('Welcome!');
});
}
}
How could I, in Symfony2, replicate Laravel's form of dependency injection, this seems like a whole cleaner way of doing things, or perhaps there is a Symfony2 way of doing things I haven't yet discovered. Any help is appreciated.
I'm not familiar with Laravel but after reading doc I believe that DI in Laravel and Symfony are quite similar after all.
From the doc:
There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.
In this case, Symfony has similar feature starting from 2.8 version which is auto wiring
In other case (meaning that class has constructor dependencies) you need to instruct your framework how to resolve these dependencies. Only difference here is that you have to do it in different ways.
In Symfony most common way is just to use yml file:
services:
mailer:
class: Mailer
arguments: ['%mailer.transport%']
But you can do it in xml or php as well (check the doc)
$container->setParameter('mailer.transport', 'sendmail');
$container
->register('mailer', 'Mailer')
->addArgument('%mailer.transport%');
But in Laravel it is the same: you need to instruct framework how to instantiate objects
$this->app->bind('HelpSpot\API', function ($app) {
return new HelpSpot\API($app->make('HttpClient'));
});
Which option to choose to setup container (yml, xml, php) is just a matter of taste.

Access Config Parameter without Container

What is the recommended way of accessing the global config parameters? I know you should inject just what you need, but the whole point of global parameters (in most cases) is to set application defaults. And I WANT the defaults to be universal, even if I allow passing in overrides on a function by function basis.
THE PROBLEM
I have a ViewVersion entity with a ViewVersionRepository where I have common functions for interacting with that entity.
One of these functions requires that I know a certain parameter from the config.yml (e.g. cms.save.newVersionSeconds so I know when it's been more than 30 minutes since the last save and I should create a new version record). The entity repository is not container aware though, so I can't access the config with the normal method:
$myParam = $container->getParameter('my.custom.param');
Inject From Controller
If I call this function from a controller, no problem I can get the config in the controller and inject the parameter into the repo function.
$myParam = $container->getParameter('my.custom.param');
$viewVersionRepository->myFunction($myParam)
Global Service
Or I can configure the the repo as a service:
gutensite_cms.view_version_repository:
class: Gutensite\CmsBundle\Entity\View\ViewVersionRepository
factory_service: 'doctrine.orm.cms_entity_manager'
factory_method: 'getRepository'
calls:
- [setLimit, ['%cms.limit.list.admin%']]
- [setNewVersionSeconds, ['%cms.save.newVersionSeconds%']]
And then set the parameter with setter injection via the calls arguments in the services.yml. And then load the service:
$viewVersionRepository = $this->container->get('gutensite_cms.view_version_repository');
Complication
However... I have a situation where I'm loading this viewVersionRepository within a doctrine onFlush event listener. And there I don't have access to the container (natively), so I can't actually load the global service. I have access to the entity though so I was loading the repo via:
$repo = $em->getRepository('GutensiteCmsBundle:View\ViewVersion);
But when you load it that way, it's not loaded as a service so the setter injection doesn't happen...
ONE SOLUTION
So I could pass the container into the global onFlush event listener service, so that I can load the ViewVersionRepository as a service (and for that matter have the container to the load the parameters if I wanted).
gutensite_cms.listener.is_versionable:
class: Gutensite\CmsBundle\EventListener\IsVersionableListener
#only pass in the services we need
arguments: [ "#gutensite_cms.entity_helper" ]
calls:
- [setContainer, ["#service_container"]]
tags:
- { name: doctrine.event_listener, event: onFlush }
But I'm told over and over and over again* to **ONLY inject the parameters you need. And to avoid injecting the entire container. This onFlush event is really quite dynamic, loading the corresponding onFlush event in any entity's repository that has an onFlush method. So in one entity repository the custom function may need access to one parameter, but in another entity repository the may need access another. So I can't really pass in just one parameter.
And it seems to me that passing the entire container makes your application far more coupled than if you were to just used the vilified $GLOBALS or CONSTANT for your global default config. So surely there is a better way to avoid both these evils. Not to mention you should NEVER inject the container into an entity repository.
So isn't there some way to access the global config parameters WITHOUT injecting the entire blessed container? Does no one EVER need global config parameters in an entity repository? Sure I could move this function to another service... but why? This is one of the basic functions of this entity, e.g. it determines if it should be versioned or not.

In Symfony2, why is it a bad idea to inject the service container, rather than individual services?

I can't find the answer to this...
If I inject the service container, like:
// config.yml
my_listener:
class: MyListener
arguments: [#service_container]
my_service:
class: MyService
// MyListener.php
class MyListener
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function myFunction()
{
$my_service = $this->container->get('my_service');
$my_service->doSomething();
}
}
then it works just as well as if I do:
// config.yml
my_listener:
class: MyListener
arguments: [#my_service]
my_service:
class: MyService
// MyListener.php
class MyListener
{
protected $my_service;
public function __construct(MyService $my_service)
{
$this->my_service = $my_service;
}
public function myFunction()
{
$this->my_service->doSomething();
}
}
So why shouldn't I just inject the service container, and get the services from that inside my class?
My list of reasons why you should prefer injecting services:
Your class is dependent only on the services it needs, not the service container. This means the service can be used in an environment which is not using the Symfony service container. For example, you can turn your service into a library that can be used in Laravel, Phalcon, etc - your class has no idea how the dependencies are being injected.
By defining dependencies at the configuration level, you can use the configuration dumper to know which services are using which other services. For example, by injecting #mailer, then it's quite easy to work out from the service container where the mailer has been injected. On the other hand, if you do $container->get('mailer'), then pretty much the only way to find out where the mailer is being used is to do a find.
You'll be notified about missing dependencies when the container is compiled, instead of at runtime. For example, imagine you have defined a service, which you are injecting into a listener. A few months later, you accidentally delete the service configuration. If you are injecting the service, you'll be notified as soon as you clear the cache. If you inject the service container, you'll only discover the error when the listener fails because of the container cannot get the service. Sure, you could pick this up if you have thorough integration testing, but ... you have got thorough integration testing, haven't you? ;)
You'll know sooner if you are injecting the wrong service. For example, if you have:
public function __construct(MyService $my_service)
{
$this->my_service = $my_service;
}
But you've defined the listener as:
my_listener:
class: Whatever
arguments: [#my_other_service]
When the listener receives MyOtherService, then PHP will throw an error, telling you that it's receiving the wrong class. If you're doing $container->get('my_service') you are assuming that the container is returning the right class, and it can take a long time to figure out that its' not.
If you're using an IDE, then type hinting adds a whole load of extra help. If you're using $service = $container->get('service'); then your IDE has no idea what $service is. If you inject with
public function __construct(MyService $my_service)
{
$this->my_service = $my_service;
}
then your IDE knows that $this->my_service is an instance of MyService, and can offer help with method names, parameters, documentation, etc.
Your code is easier to read. All your dependencies are defined right there at the top of the class. If they are scattered throughout the class with $container->get('service') then it can be a lot harder to figure out.
Your code is easier to unit test. If you're injecting the service container, you've got to mock the service container, and configure the mock to return mocks of the relevant services. By injecting the services directly, you just mock the services and inject them - you skip a whole layer of complication.
Don't be fooled by the "it allows lazy loading" fallacy. You can configure lazy loading at configuration level, just by marking the service as lazy: true.
Personally, the only time injecting the service container was the best possible solution was when I was trying to inject the security context into a doctrine listener. This was throwing a circular reference exception, because the users were stored in the database. The result was that doctrine and the security context were dependent on each other at compile time. By injecting the service container, I was able to get round the circular dependency. However, this can be a code smell, and there are ways round it (for example, by using the event dispatcher), but I admit the added complication can outweigh the benefits.
Besides all disadvantages explained by others (no control over used services, run time compilation, missing dependencies, etc.)
There is one main reason, which breaks the main advantage of using DIC - Dependencies replacement.
If service is defined in library, you wont be able to replace it dependencies with local ones filling your needs.
Only this reason is strong enough, to not inject whole DIC. You just break whole idea of replacing dependencies since they are HARDCODED! in service;)
BTW. Don't forget to require interfaces in service constructor instead of specific classes as much as you can - again nice dependencies replacement.
EDIT: Dependencies replacement example
Service definition in some vendor:
<service id='vendor_service' class="My\VendorBundle\SomeClass" />
<argument type="service" id="vendor_dependency" />
</service>
Replacement in your app:
<service id='vendor_service' class="My\VendorBundle\SomeClass" />
<argument type="service" id="app_dependency" />
</service>
This allows you to replace vendor logic with your customized one, but don't forget to implement required class interface. With hardcoded dependencies you're not able to replace dependency in one place.
You can also override vendor_dependency service, but this will replace it in all places not only in vendor_service.
It is not a good idea because you're making your class dependent on the DI. What happens when some day you decide to pull out your class and use it on an entirely different project? Now I'm not talking about Symfony or even PHP, I'm talking generally. So in that case you have to make sure the new project uses the same kind of DI mechanism with the same methods supported or you get exceptions. And what happens if the project does not use DI at all, or uses some cool new DI implementation? You have to go through your whole codebase and change things to support the new DI. In large projects this can be problematic and costly, especially when you're pulling more than just one class.
It is best to make your classes as independent as possible. This means keeping the DI out of your usual code, something like a 3rd person who decides what goes where, points where the stuff should go, but doesn't go there and do it himself. This is how I understand it.
Although, as tomazahlin said, I agree that in Symfony projects in rare occasion it helps prevent circular dependencies. That's the only example where I'd use it and I'd make damn sure that's the only option.
Injecting the whole container is not a good idea in general. Well, it works, but why injecting the whole container, while you only need a few other services or parameters.
Sometimes you want to inject the whole container to avoid circular references, because if you inject the whole container, you get "lazy loading" of the services you require. An example would be doctrine entity listeners.
You can get the container from every class that is "Container Aware" or has access to the kernel.

How to access the configuration parameters from the model layer in Symfony 2?

Is there a way to access the configuration parameters in config.yml from the model layer? From the controller I can use $this->container->getParameter('xyz'). But how can it be done from a class in the Model layer?
In symfony2 Entities are designed as POPOs, meaning that they shouldn't really have access to anything outside of their scope.
If you need some config option in one of your entities, consider passing it as a parameter from the controller like so:
$entityName->methodName($param1, $this->container->getParameter('xyz'));
This could (will) break DIC pattern, but you could use a singleton class to "globalize" what you need.
To feed your globals, use bootmethod from Bundle class (where you can access DIC stuff hence configuration).
Or more simple, add a static field to your Entity.
Quick & dirty solution, don't abuse it ;-)
You can use Dependency Injection and add your model to your services.yml file, and like every other service you make you can provide other services as constructor parameters. The only downside is you call $derp = $this->get("your_service_name"); instead of $derp = new Derp();.
For example:
# src/Derp/LolBundle/Resources/config/services.yml
services:
derp:
class: \Derp\LolBundle\Entity\Message
arguments: [#service_container]
#service_container is a service found using php app/console container:debug. It will function identically to $this->container in your controllers and it is provided to the constructor of your class. See here for more information on how to use service containers.
As previously mentioned they are POPOs (Plain Old PHP Objects) and the previous method of dependency injection is poor choice simply because you will have to remember to provide your model entity with the same object every time you use it (which is a hassle) and Symfony2 services are a way to mitigate that pain.

Resources