Symfony: 8 – Annotations

Annotations

The default Symfony2 FrameworkBundle implements a basic but robust and flexible MVC framework. SensioFrameworkExtraBundle extends it to add sweet conventions and annotations. It allows for more concise controllers. Download the bundle and put it under the Sensio\Bundle\ namespace. Then, like for any other bundle, include it in your Kernel class. If you plan to use or create annotations for controllers, make sure to update your autoload.php by adding the following line:

public function registerBundles()
{
    $bundles = array(
        ...
 
        new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
    );
 
    ...
}
 
Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

Annotations are a great way to easily configure your controllers, from the routes to the cache configuration. Even if annotations are not a native feature of PHP, it still has several advantages over the classic Symfony2 configuration methods:

  • Code and configuration are in the same place (the controller class)
  • Simple to learn and to use
  • Concise to write
  • Makes your Controller thin (as its sole responsibility is to get data from the Model)
  • If you use view classes, annotations are a great way to avoid creating view classes for simple and common use cases

The following annotations are defined by the bundle:

  • @Route
  • @Method
  • @ParamConverter
  • @Template
  • @Cache
  • @Securityc

This example shows all the available annotations in action:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
 
/**
 * @Route("/blog")
 * @Cache(expires="tomorrow")
 */
class AnnotController extends Controller
{
    /**
     * @Route("/")
     * @Template
     */
    public function indexAction()
    {
        $posts = ...;
 
        return array('posts' => $posts);
    }
 
    /**
     * @Route("/{id}")
     * @Method("GET")
     * @ParamConverter("post", class="SensioBlogBundle:Post")
     * @Template("SensioBlogBundle:Annot:show.html.twig", vars={"post"})
     * @Cache(smaxage="15", lastmodified="post.getUpdatedAt()", etag="'Post' ~ post.getId() ~ post.getUpdatedAt()")
     * @Security("has_role('ROLE_ADMIN') and is_granted('POST_SHOW', post)")
     */
    public function showAction(Post $post)
    {
    }
}

Leave a Reply