Wednesday, January 25, 2012

Symfony2 Services Notes

A service has a class, arguments to pass in on instantiation (can be other services @mailer) (must be present in constructor)

arguments can be optional (@?my_mailer),

outside of the constructor, with the calls: yml line under class, e.g. - [ setMailer, [ @my_mailer ] ]

services are by default public.

If two services have common dependencies or calls requirements, extend each from an abstract, and use parent: abstract_class_name for each service,

with the abstract defined higher up - set with abstract: true, and the calls on these.

You can override the calls parameter on the service that extends a parent, by adding calls to this too, and using the same key. Note that it is then called twice, so if you want to add to an array you can (otherwise it gets replaced with the last call). You could remove parent param from extender to stop this.

Factories can be used to make a service (if more complex than just passing other services in as arguments), first define the factory,

then use factory_service: yml line referencing the factory key. For the method used within this factory, define it as factory_method: , e.g. get.

For arguments you wish to pass into the get method, use arguments: - an array - @templating for example.

Services can have tags, which implies that the service is to be used for a specific purpose.

No comments: