Doctrine annotations VS PHP8 attributes
GraphQLite is heavily relying on the concept of annotations (also called attributes in PHP 8+).
Doctrine annotations
Historically, attributes were not available in PHP and PHP developers had to "trick" PHP to get annotation support. This was the purpose of the doctrine/annotation library.
Using Doctrine annotations, you write annotations in your docblocks:
use TheCodingMachine\GraphQLite\Annotations\Type;
/**
* @Type
*/
class MyType
{
}
Please note that:
- The annotation is added in a docblock (a comment starting with "
/**
") - The
Type
part is actually a class. It must be declared in theuse
statements at the top of your file.
- PhpStorm via the PHP Annotations Plugin
- Eclipse via the Symfony 2 Plugin
- Netbeans has native support
We strongly recommend using an IDE that has Doctrine annotations support.
PHP 8 attributes
Starting with PHP 8, PHP got native annotations support. They are actually called "attributes" in the PHP world.
The same code can be written this way:
use TheCodingMachine\GraphQLite\Annotations\Type;
#[Type]
class MyType
{
}
GraphQLite v4.1+ has support for PHP 8 attributes.
The Doctrine annotation class and the PHP 8 attribute class is the same (so you will be using the same use
statement at the top of your file).
They support the same attributes too.
A few notable differences:
- PHP 8 attributes do not support nested attributes (unlike Doctrine annotations). This means there is no equivalent to the
annotations
attribute of@MagicField
and@SourceField
. - PHP 8 attributes can be written at the parameter level. Any attribute targeting a "parameter" must be written at the parameter level.
Let's take an example with the #Autowire
attribute:
PHP 7+
/**
* @Field
* @Autowire(for="$productRepository")
*/
public function getProduct(ProductRepository $productRepository) : Product {
//...
}
PHP 8
#[Field]
public function getProduct(#[Autowire] ProductRepository $productRepository) : Product {
//...
}