Annotations for PHP
, (*1)
PHP does not have any kind of native annotation (AKA attributes from .NET world) so if you'd like to implement your own annotation framework think of using this first and save some time., (*2)
Installation
Using composer is quite simple, just run the following command:, (*3)
$ 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, (*4)
``` php
class MyCustomAnnotation
{, (*5)
}, (*6)
Then you'll have to extend the **Annotation** class from the library
``` php
use PHPAnnotations\Annotations\Annotation;
class MyCustomAnnotation extends Annotation
{
}
Add some logic to it
``` php
use PHPAnnotations\Annotations\Annotation;, (*7)
class MyCustomAnnotation extends Annotation
{
private $name;
private $surname;, (*8)
public function __constructor($name, $surname)
{
$this->name = $name;
$this->surname = $surname;
}
public function GetFullName()
{
return "$this->name $this->surname";
}
}, (*9)
Now our beautiful annotation is ready to go!
#### Use the annotation
Create a class to used to test the annotation
``` php
class MyTestClass
{
}
And add the annotation through the docs, (*10)
``` php
/**
* @MyCustom(name = "Thomas", surname = "Cocchiara")
**/
class MyTestClass
{, (*11)
}, (*12)
Now we're ready to test it out!
``` php
use use PHPAnnotations\Reflection\Reflector;
$myObject = new MyTestClass();
$reflector = new Reflector($myObject);
echo $reflector->getClass()->getAnnotation("MyCustom")->GetFullName();
Hope you guys find this library useful., (*13)
Please share it and give me a feedback :), (*14)
Thomas, (*15)