Attributes in Hack

First there where PHP annotations

The introduction of PHP style annotation by (mis)using comments always felt like a bad idea for me. Maybe because I think a comment cannot have any meaning beside some meaningful information for a developer or a documenting system that parses the comments to extract the information. But other than it should be possible to remove all comments without changing the behaviour of a progam.

So a comment should be structured in a proper way but should not be used in an automatic way to add meaning to code.

use Doctrine\ORM\Mapping as ORM;
 * @ORM\Entity
 * @ORM\Table(name="blog")
class Person {}

In this example a comment is added in front of a class to tell doctrine what this class is. This is a poor mans implementation of Annotations in Java.

But then Hack introduced attributes

In the Hack language attributes are introduced that replaces this somewhat poor solution and introduces native attributes that can be added to a class or a function.

Class attributes

<<Entity, Table("blog")>>
class Person {

With reflection these attributes can be retrieved at runtime.

$rc = new \ReflectionClass(Person::class);

Function attributes

Attributes can be placed above a method/function. It can be used for a MVC framework to determine the entrypoint and routing. Something that is used a lot in Java EE. Together with a typed return value HACK is almost looking like Java.

class IndexController {
  public function list(int $start) : JsonResponse {}

Argument attributes

Also attributes in the arguments of a function are supported. With this some extra information can be added to an argument. Something that is not possible at all with the PHP style annotations.

function baz(<> int $id) {}

$rf = new \ReflectionFunction('baz');
$attrs = $rf->getParameters();