Symfony2 can handle configuration in different formats: YAML, XML, and annotations. The main configuration files within app/config are provided with the YAML format. XML is usually harder to read, and is used only with third-party bundles.

While both YAML and XML configuration are pretty straightforward and need no explanations, we should stop by annotations for a while. As an example, see the AppBundle/Controller/DefaultController class:

namespace AppBundleController;

use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SymfonyBundleFrameworkBundleControllerController;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        // replace this example code with whatever you need
        return $this->render('default/index.html.twig', array(
            'base_dir' => realpath(
                $this->container
                     ->getParameter('kernel.root_dir').'/..'),
        ));
    }
}

If you are familiar with the PHPDoc or JavaDoc convention, you will recognize@token in the preceding example. You may, however, notice one small detail—it’s not a standard token. In fact, this token means something; it’s not just a comment. In our example, the route annotation (imported through the use keyword here) configures routing with the name homepage and the / URL.

Annotations are usually easy to handle and the most convenient way to configure various aspects of your application but at the same time they are the most controversial.

As you can see, it’s handy to have a URL configuration in the same place where the code exists. However, in the case of routing and controllers, it may become hard to navigate over the code, and may cause errors when multiple coders are on board the project.

Some developers avoid annotations because they believe code within comments should not be “parsed”, as this is against the idea of having comments. It is worth mentioning that annotations should never be used within the code you want to reuse or keep free from Symfony2 dependencies.

Advertisements