Strategy Template in Symfony2

I am trying to create a simple service for rendering various types of pages. The basic concept has something like:

$somePageType = new PageType(...); $this->get('page.service')->render($somePagetype); 

... to be created as a strategy template . Page types will implement the interface using the render method, and page.service will implement it. The problem is that I would like to use Doctrine in page type classes. What are my options? I would like to avoid creating a service for each of these classes. Is it possible? Is it possible to make them containers without maintenance? Perhaps in the future, for certain types of pages, something more than just the Doctrine may be required, so I must remember that.

+7
source share
2 answers

I assume PageType is an example of a strategy class. In this case, you can inject page.service dependencies, and you will not need to define strategies as services.

Each strategy probably depends on different objects, so I think you could make them ContainerAware . Here is an example of how to do it.

 // This is the page.service class class MyPageService { public function render(PageTypeInterface $page_type) { $page_type->setContainer($this->container); // do stuff } } // This is the type strategy class MyStrategyType extends ContainerAware implements PageTypeInterface { // you can access the container after MyPageService has injected it. } 

Thus, each strategy will expand ContainerAware , and page.service will introduce a container.


EDIT

If all your strategies depend on the same services, I would introduce them instead of the entire container.

 class MyPageService { public function render(PageTypeInterface $page_type) { $page_type->setService($this->container->get('my_service')); // do stuff } } 
+1
source

Services are exactly what you want here. Ability to make dependencies for a specific strategy. Then entering a specific strategy into the controller (it can also be a dynamic renderer that selects a strategy at runtime).

ContainerAware is a very bad practice, it associates this object with all the services in the container. Therefore, I highly recommend avoiding this.

+3
source

All Articles