PHP – Magic Annotations

October 9, 2018 Library, PHP

Have you ever heard of Attributes (so called in .NET) or Annotations? Have you ever wondered to use them in PHP?

Now’s possible thanks to the PHP Magic Annotations library that we created.

For whoever doesn’t know what an annotation is: annotations are most likely metadata added to your code.

C# example:

[PrimaryKey]public string email;

In the example above, PrimaryKey is an annotation which adds the PrimaryKey metadata to the email parameter. That metadata can be used later in the code to perform specific actions.

PS: You can find the library at https://github.com/ThomasSquall/PHPMagicAnnotations.

So, how does it work?

The library takes advantage of the getDocComment method of the ReflectionClass class (more info at: http://php.net/manual/en/reflectionclass.getdoccomment.php).

This function returns all the extended comments of the class (comments in between of /* and */)

Quick guide

Installation

Using composer is quite simple, just run the following command:

$ composer require thomas-squall/php-magic-annotations

Usage

Create a new Annotation

First you have to create a new class. In this example the class will be called MyCustomAnnotation

class MyCustomAnnotation{}

Then you’ll have to extend the Annotation class from the library

use PHPAnnotations\Annotations\Annotation;
class MyCustomAnnotation extends Annotation{
}

Add some logic to it

use PHPAnnotations\Annotations\Annotation;
class MyCustomAnnotation extends Annotation{
    private $name;    
private $surname;        
public function __constructor($name, $surname)    
{        
$this->name = $name; 
       $this->surname = $surname;
    }        
public function GetFullName()    
{        
return "$this->name $this->surname";    
}}

Now our beautiful annotation is ready to go!

Use the annotation

Create a class to used to test the annotation

class MyTestClass{}

And add the annotation through the docs

/** * [MyCustom(name = "Thomas", surname = "Cocchiara")] **/class
 MyTestClass{   }

Now we’re ready to test it out!

use PHPAnnotations\Reflection\Reflector;
$myObject = new MyTestClass();
$reflector = new Reflector($myObject);
echo $reflector->getClass()->getAnnotation("MyCustom")->GetFullName();

Hope you guys find this library useful.

Please share it and give me a feedback 🙂