Download e-book for kindle: A Year With Symfony Writing healthy, reusable Symfony2 by Matthias Noback

Service ids instead of references Whenever you request the object_renderer service, all the specific renderers are instantiated too. Depending on the cost of instantiating these renderers it could be a good idea to add support for lazy-loading. This can be accomplished by making the ObjectRenderer container-aware and by injecting service ids, not the services themselves: 43 Service patterns class LazyLoadingObjectRenderer { private $container; private $renderers; public function __construct(ContainerInterface $container) { $this->container = $container; } public function addRenderer($name, $renderer) { $this->renderers[$name] = $renderer; } public function render($object) { foreach ($this->renderers as $name => $renderer) { if (is_string($renderer)) { // $renderer is assumed to be a service id $renderer = $this->container->get($renderer); } // check if the renderer is an instance of RendererInterface ...

3 A collection of services In most situations you inject specific services as constructor or setter arguments. But sometimes you need to inject a collection of services, that are treated in the same way, for instance when you want to provide several alternative ways (strategies) to achieve something: class ObjectRenderer { private $renderers; public function __construct(array $renderers) { $this->renderers = $renderers; } public function render($object) Service patterns 37 { foreach ($this->renderers as $renderer) { if ($renderer->supports($object) { return $renderer->render($object); } } } } In a service definition this may look like: This collection type argument will be converted to an array, containing the services referenced by their ids: array( 0 => ...

Response instanceof Response) { ... } } As you may remember from the Symfony documentation, a controller should return a Response object. If it doesn’t, some other part of the application should be able to convert the return value to a Response object in some way or another. 6 Enter the view layer When you choose to return a Response object directly from your controller, you can thereby effectively by-pass the templating engine: class SomeController { public function simpleAction() { return new Response( '

Pure old-fashioned HTML

' ); } } However, when you return anything else (though usually an array of template variables), this return value needs to be converted to a Response object before it can be used as a decent response to be sent back to the client.

Download PDF sample

A Year With Symfony Writing healthy, reusable Symfony2 by Matthias Noback


by George
4.2

Rated 4.20 of 5 – based on 36 votes