2

Developing my Symfony2 application, i would like to, kind of like in Ruby on Rails, to have methods available in all controllers. In RoR controllers simply inherit after ApplicationController and that is where you put all the methods. But what is the Symfony way, what is good practice here?

Functionality I want is very simple actually, something similar to this:

public function showAction()
{
    $user = $this->container->get('security.context')->getToken()->getUser();
}

I can load current user here, and I would like this function to be terminated before every action, without, of course, copying the code into every single controller.

1
  • Be aware that the standard Symfony 2 base controller class already has a getUser() method. It's worth taking a look at the source code to see what it can do.
    – Cerad
    Sep 7, 2014 at 15:54

1 Answer 1

6

You can use services for this.

Acme/DemoBundle/MyService/MyService.php

<?php
namespace Acme/DemoBundle/MyService

class MyService {

   public function myFunction(){
        [...]
   }

}

Acme/DemoBundle/Resources/config/services.yml

services:
    my_service:
        class: Acme/DemoBundle/MyService/MyService

Or .xml version

Acme/DemoBundle/Resources/config/services.xml

<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd"
>
    <services>
        <service id="my_service" class="Acme\DemoBundle\MyService\MyService">

        </service>
    </services>
</container>

Then in a controller

Acme/DemoBundle/Controller/MyController.php

$this->container->get("my_service")->myFunction();

To make it available in all your bundles just update each bundle's services config file accordingly.

Documentation is available here

3
  • should i make special folder for MyService class inside of Acme\DemoBundle directory?
    – Leo
    Sep 7, 2014 at 11:21
  • You can pretty much do as you please but yes that is good practice.
    – Tom Tom
    Sep 7, 2014 at 11:22
  • To clarify, for this specific example yes. But you can do as you like as long as you update the namespace accordingly.
    – Tom Tom
    Mar 5, 2015 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.