• Home
  • blog
  • Your Own Custom Annotations – More than Just Comments!

Your Own Custom Annotations – More than Just Comments!

In this article, we are going to look at how we can create and use our own custom annotations in a Symfony 3 application. You know annotations right? They are the docblock metadata/configuration we see above classes, methods and properties. You’ve most likely seen them used to declare Controller routes (@Route()) and Doctrine ORM mappings (@ORM()), or even to control access to various classes and methods in packages like Rauth. But have you ever wondered how can you use them yourself? How you can define your own annotation and then use it to read information about a class or method without actually loading it?

Snippet of code with custom annotations

Before we do this, a small disclaimer is in order. Annotations have nothing to do with Symfony. They are a concept developed as part of the Doctrine project to solve the problem of mapping ORM information to class methods.

In this article we are going to build a small reusable bundle called WorkerBundle. Reusable yes, but still only for demo purposes so not really package-able. We’re going to develop a small concept that allows the definition of various Worker types which “operate” at various speeds and which can then be used by anyone in the application. The actual worker operations are outside the scope of this post, since we are focusing on setting up the system to manage them (and discover them via annotations).

To see where we’re going, you can check out this repository and follow the instructions covered there for setting up the bundle in your local Symfony app.

The Workers

The workers will implement an interface that requires one method: ::work(). Inside our new WorkerBundle, let’s create a Workers/ directory to keep things tidy and add the interface there:


namespace WorkerBundleWorkers;

interface WorkerInterface
     * Does the work
     * @return NULL
    public function work();

The Annotation

Each worker has to implement the above interface. That’s clear. But aside from that, we need them to also have an annotation above the class in order to find them and read some metadata about them.

Doctrine maps the docblock annotation to a class whose properties represent the keys inside the annotation itself. Let’s create our own and see this in practice.

Continue reading %Your Own Custom Annotations – More than Just Comments!%