Symfony

Playing with annotations in symfony 2

Annotation is a term used in computer programming to refer to documentation and comments that may be found on code logic. Annotation is typically ignored once the code is executed or compiled.

Sometimes programmers will anticipate that those learning a programming language such as HTML, or those who may be modifying the programming at a later date, will require an explanation of the rationale behind the logic or even an explanation of how the logic accomplishes its purpose or goal. Thus, an annotation, or explanation, will be included within the code.

— Definition from Techopedia

Use of annotation in Symfony 2

Symfony 2 uses annotations for Doctrine mapping information, Routing and Validation configuration etc. By the way, It’s optional but, powerful and convenient for programmers. Same thing can be done in XML, YAML or in PHP but writing Routing or validation rule in same file seems more convenient to programmers.

Annotations are great way to easily configure the controllers, for every configurations defined into the settings. By default all annotations are enabled. You can disable some annotations by making it false in setting.

<?php
// load the profiler
$container->loadFromExtension('sensio_framework_extra', array(
    'router'      => array('annotations' => true),
    'request'     => array('converters' => true, 'auto_convert' => true),
    'view'        => array('annotations' => true),
    'cache'       => array('annotations' => true),
    'security'    => array('annotations' => true),
    'psr_message' => array('enabled' => false), // Defaults to true if the PSR-7 bridge is installed
));
?>

Prerequisite

Using annotation requires some prerequisites

 

Installation

You can use composer to install SensioFrameworkExtraBundle.

$ composer require sensio/framework-extra-bundle

Composer

If you want to use annotations for Controllers, you need to update the autoload.php file by adding below line into it.

Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, ‘loadClass’));

code

By default following annotations are enabled in bundle:

 

#1 Routes

@Route annotations maps route patterns with the Controller. You can define routes, parameters ands its datatypes and default parameter with annotations. E.g.,

<?php
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
 
class TestController extends Controller {
/**
 * @Route("/blogs/{id}", requirements={"id" = "\d+"}, defaults={"id" = 549})
 */
public function showAction($id)
{
     return $id
}
}
?>

#2 ParamConverter

The @ParamConverter annotation calls converters to convert request parameters to objects. These objects are stored as request attributes and so they can be injected as controller method arguments. e.g.,

<?php
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
/**
 * @Route("/blog/{id}")
 * @ParamConverter("post", class="SensioBlogBundle:Post")
 */
public function showAction(Post $post)
{
    ....
}
?>

What it does

ParamConverter tries to get a post object from request. If POST object found, a new post attribute is defined otherwise, it returns 404.

 

#3 Templates

The @Template annotations associates a template with the Controller. E.g.,

<?php
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
 * @Template("SensioBlogBundle:Post:abc.html.twig")
 */
public function showAction($id)
{
    return array('post' => $post);
}
?>

#4 Cache

@Cache enables http caching

<?php
/**
 * @Cache(expires="today")
 */
class TestController extends Controller
{
    /**
    * @Cache(expires="+5 days")
    */
    public function showAction()
    {
    }
}
?>

In the above example two cache expiries are defined and conflicting each other. In that case “+5 days” would be effective.

 

#5 Security

@Security annotations restricts access and prevent the unauthorized access of Controllers

<?php
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
class TestController extends Controller
{
    /**
    * @Security("has_role('ROLE_ADMIN') or has_role(‘ROLE_EDITOR’)")
    */
    public function HowAction()
    {
        // ...
    }
}
?>

Using annotation with symfony is fun for a PHP guy, Try this. Please write comments if you get any issue.

Cheers!!!

6 Comments

  1. Hiya, I’m really glad I have found this information. Today bloggers publish just about gossip and internet stuff and this is really irritating. A good blog with interesting content, that’s what I need. Thanks for making this site, and I will be visiting again. Do you do newsletters? I Cant find it.

    1. Thanks. Soon we will have news letter sections. I am just building it up.

  2. […] one of my previous article, I got a question from one of the reader — what is Composer? How can we use it?  PHP […]

  3. Would you mind basically if I cite a couple of your discussions given that I deliver you credit as well as article sources returning to your webblog? My web portal is in the identical market as your site and my prospects would definitely use some of the advice you actually present at this website. Please let me know if this is okay with you. Adios for now!

    1. I have no issue if my experience is benefitting someone. Plz use the content but request you to mention spokenbyyou.com as source of the content.

  4. I am curious to find out what blog platform you happen to be working with? I’m experiencing some minor security problems with my latest blog and I would like to find something more secure. Do you have any recommendations?

Leave a Reply

Your email address will not be published. Required fields are marked *