Annotations Parser

It is the first time that an annotations parser component is written in C for the PHP world. Phalcon\Annotations is a general purpose component that provides ease of parsing and caching annotations in PHP classes to be used in applications.

Annotations are read from docblocks in classes, methods and properties. An annotation can be placed at any position in the docblock:

<?php/**
* This is the class description
*
* @AmazingClass(true)
*/classExample{/**
* This a property with a special feature
*
* @SpecialFeature
*/protected$someProperty;/**
* This is a method
*
* @SpecialFeature
*/publicfunctionsomeMethod(){// ...}}

An annotation has the following syntax:

/**
* @Annotation-Name
* @Annotation-Name(param1, param2, ...)
*/

Also, an annotation can be placed at any part of a docblock:

<?php/**
* This a property with a special feature
*
* @SpecialFeature
*
* More comments
*
* @AnotherSpecialFeature(true)
*/

The parser is highly flexible, the following docblock is valid:

<?php/**
* This a property with a special feature @SpecialFeature({
someParameter='the value', false
}) More comments @AnotherSpecialFeature(true) @MoreAnnotations
**/

However, to make the code more maintainable and understandable it is recommended to place annotations at the end of the docblock:

<?php/**
* This a property with a special feature
* More comments
*
* @SpecialFeature({someParameter='the value', false})
* @AnotherSpecialFeature(true)
*/

Factory

There are many annotations adapters available (see Adapters). The one you use will depend on the needs of your application. The traditional way of instantiating such an adapter is as follows:

The Factory loader provides more flexibility when dealing with instantiating annotations adapters from configuration files.

Reading Annotations

A reflector is implemented to easily get the annotations defined on a class using an object-oriented interface:

<?phpusePhalcon\Annotations\Adapter\MemoryasMemoryAdapter;$reader=newMemoryAdapter();// Reflect the annotations in the class Example$reflector=$reader->get('Example');// Read the annotations in the class' docblock$annotations=$reflector->getClassAnnotations();// Traverse the annotationsforeach($annotationsas$annotation){// Print the annotation nameecho$annotation->getName(),PHP_EOL;// Print the number of argumentsecho$annotation->numberArguments(),PHP_EOL;// Print the argumentsprint_r($annotation->getArguments());}

The annotation reading process is very fast, however, for performance reasons it is recommended to store the parsed annotations using an adapter. Adapters cache the processed annotations avoiding the need of parse the annotations again and again.

Phalcon\Annotations\Adapter\Memory was used in the above example. This adapter only caches the annotations while the request is running and for this reason the adapter is more suitable for development. There are other adapters to swap out when the application is in production stage.

Types of Annotations

Annotations may have parameters or not. A parameter could be a simple literal (strings, number, boolean, null), an array, a hashed list or other annotation:

Practical Usage

Next we will explain some practical examples of annotations in PHP applications:

Cache Enabler with Annotations

Let’s pretend we’ve created the following controller and you want to create a plugin that automatically starts the cache if the last action executed is marked as cacheable. First off all, we register a plugin in the Dispatcher service to be notified when a route is executed:

CacheEnablerPlugin is a plugin that intercepts every action executed in the dispatcher enabling the cache if needed:

<?phpusePhalcon\Events\Event;usePhalcon\Mvc\Dispatcher;usePhalcon\Mvc\User\Plugin;/**
* Enables the cache for a view if the latest
* executed action has the annotation @Cache
*/classCacheEnablerPluginextendsPlugin{/**
* This event is executed before every route is executed in the dispatcher
*/publicfunctionbeforeExecuteRoute(Event$event,Dispatcher$dispatcher){// Parse the annotations in the method currently executed$annotations=$this->annotations->getMethod($dispatcher->getControllerClass(),$dispatcher->getActiveMethod());// Check if the method has an annotation 'Cache'if($annotations->has('Cache')){// The method has the annotation 'Cache'$annotation=$annotations->get('Cache');// Get the lifetime$lifetime=$annotation->getNamedParameter('lifetime');$options=['lifetime'=>$lifetime,];// Check if there is a user defined cache keyif($annotation->hasNamedParameter('key')){$options['key']=$annotation->getNamedParameter('key');}// Enable the cache for the current method$this->view->cache($options);}}}

Now, we can use the annotation in a controller:

<?phpusePhalcon\Mvc\Controller;classNewsControllerextendsController{publicfunctionindexAction(){}/**
* This is a comment
*
* @Cache(lifetime=86400)
*/publicfunctionshowAllAction(){$this->view->article=Articles::find();}/**
* This is a comment
*
* @Cache(key='my-key', lifetime=86400)
*/publicfunctionshowAction($slug){$this->view->article=Articles::findFirstByTitle($slug);}}

Private/Public areas with Annotations

You can use annotations to tell the ACL which controllers belong to the administrative areas:

<?phpusePhalcon\Acl;usePhalcon\Acl\Role;usePhalcon\Acl\Resource;usePhalcon\Events\Event;usePhalcon\Mvc\User\Plugin;usePhalcon\Mvc\Dispatcher;usePhalcon\Acl\Adapter\MemoryasAclList;/**
* This is the security plugin which controls that users only have access to the modules they're assigned to
*/classSecurityAnnotationsPluginextendsPlugin{/**
* This action is executed before execute any action in the application
*
* @param Event $event
* @param Dispatcher $dispatcher
*
* @return bool
*/publicfunctionbeforeDispatch(Event$event,Dispatcher$dispatcher){// Possible controller class name$controllerName=$dispatcher->getControllerClass();// Possible method name$actionName=$dispatcher->getActiveMethod();// Get annotations in the controller class$annotations=$this->annotations->get($controllerName);// The controller is private?if($annotations->getClassAnnotations()->has('Private')){// Check if the session variable is active?if(!$this->session->get('auth')){// The user is no logged redirect to login$dispatcher->forward(['controller'=>'session','action'=>'login',]);returnfalse;}}// Continue normallyreturntrue;}}

Annotations Adapters

This component makes use of adapters to cache or no cache the parsed and processed annotations thus improving the performance or providing facilities to development/testing: