Symfony2: annotations VS yaml

When we have to map a doctrine entity, we have to establish a new route or we have to establish a new lifecycle callback in our Symfony2 project, we have to made a choose, what technique will we use? We have two options (XML and YAML are considered the same technique with different markup languages):

  • annotations. Annotations are set in the comments area of a controller function and they are related to it. For example, if we want to stablish the route to the home page in our AppBundle we should do the following:

    [php]
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

    class HomeController extends Controller
    {
    /**
    * @Route("/", "name=web_home")
    */
    public function indexAction()
    {
    // …
    }
    }[/php]

    • Advantages: You have the routing or mapping info near your code, you don’t have to go to another file to check that info. It’s simple and easy to find.
    • Disadvantages: Maybe you prefer to have all routings in a separate file to compare or manage them.
  • yaml. The equivalent previous route declaration would be in YML editing config/routing.yml and adding one line:

    [yaml]
    web_home:
    path: /
    defaults: { _controller: AppBundle:Home:index }
    [/yaml]

    • Advantages: You have all your routings and mappings in one file, and it’s clearer to compare them or manage the routes altogether
    • Disadvantages: You must go to another file to look at it.

In both cases, we have to enable the routings of our App Controller by including them in app/config/routing.yml:

[php]
# import routes from a controller class
post:
resource: "@SensioBlogBundle/Controller/PostController.php"
type: annotation
[/php]

* In case of YML we don’t have to explicit set type property

Fabien Potencier (Symfony’s Founder) prefer annotations and he gives his opinion in an article.

I don’t think one of this techniques is better than the other, just take the one you prefer

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.