Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place common business logic for all pages in symfony2

Tags:

symfony

dry

I am now working on my first symfony2 project. I have created a service, and I need to call it for every controllers to generate a html which is necessary throughout the all pages in my website.

So I created a BaseController class which extends Symfony\Bundle\FrameworkBundle\Controller\Controller class and tried to place the code in this BaseController class. Now whenever I call from the constructor:

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

or

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

I got error:

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

The container object has not been initialized. What is the solution to this problem? How DRY method is followed in symfony2, if I want to place left panel or header in all pages which contains dynamic data?

Thanks in advance.

like image 778
sumanchalki Avatar asked Jan 18 '23 06:01

sumanchalki


1 Answers

You shouldn't use the constructor in your controller class, especially when you inherit from Symfony Controller: that way you get the container after the object instantiation (the DIC will call the setContainer method inherited from Symfony's Controller).

In general, for your first experiments, use the services in the action methods; if there is some cross-cutting logic that you need to execute in every request you could consider registering some event listeners (see the "Internals" docs in the Symfony website).

When you get more confidence with the framework you can start thinking about not inheriting Symfony's Controller, registering your controller classes in the DIC and injecting the services that you need manually (eventually implementing some logic in the constructor).

like image 105
Aldo Stracquadanio Avatar answered Jan 25 '23 14:01

Aldo Stracquadanio