Where to put common business logic for all pages in symfony2

Now I am working on my first symfony2 project. I created a service and I need to call it for each controller to create the html that is needed on all pages of my website.

So, I created a BaseController class that extends the Symfony \ Bundle \ FrameworkBundle \ Controller \ Controller class and tried to put the code in this BaseController class. Now when I call from the constructor:

$my_service = $this->get('my_service'); 

or

 $my_service = $this->container->get('my_service'); 

I got an error:

 Call to a member function get() on a non-object. 

The container object is not initialized. What is the solution to this problem? How should I use the DRY method in symfony2 if I want to place the left pane or title on all pages containing dynamic data?

Thanks in advance.

+4
source share
3 answers

You should not use the constructor in your controller class, especially if you inherit from Symfony Controller: this way you get the container after creating the object (DIC will call the setContainer method inherited from Symfony Controller).

In general, for your first experiments, use services in action methods; if there is some cross-cutting logic that you need to execute in each request, you can consider registering some event listeners (see the Internal documents on the Symfony website).

When you gain more confidence in the structure, you can start thinking about not inheriting Symfony Controller by registering your controller classes in the DIC and manually inserting the services you need (eventually implementing some logic in the constructor).

+5
source

I know that this is not the answer you need, but if you need some kind of html on all pages, I think that using the service the way you do is incorrect.

I think you know about the branch and the ability to use the layout to host common code. But you can also embed a controller:

 {% render "AcmeArticleBundle:Article:recentArticles" %} 

Inside recentArticlesAction, you can put your code and return a template. Thanks to this, you can get custom html in each of your templates! See symfony docs for more details: http://symfony.com/doc/current/book/templating.html#embedding-controllers

+4
source

Business logic is all user code that you write for your application that is not structured (for example, routing and controllers). Domain classes, Doctrine entities, and the regular PHP classes that are used as services are good examples of business logic. Link

0
source

Source: https://habr.com/ru/post/1401004/


All Articles