Rob Olmos explained it right:
Annotations basically let you inject behavior and can promote decoupling.
In my words I´d say that these annotations are valuable especially in context of reflection where you gather (additional) metadata about the class/method/property you are inspecting.
Another example instead of ORM: Dependency Injection frameworks. The upcoming FLOW3 framework for exmaple uses docComments/annotations to identify which objects are injected in an instance created from a DI container instead of specifying it in an XML configuration file.
Oversimplified example following:
You have two classes, one Soldier
class and a Weapon
class. A Weapon
instance gets injected in a Soldier
instance. Look at the definition of the two classes:
class Weapon {
public function shoot() {
print "... shooting ...";
}
}
class Soldier {
private $weapon;
public function setWeapon($weapon) {
$this->weapon = $weapon;
}
public function fight() {
$this->weapon->shoot();
}
}
If you would use this class and inject all dependencies by hand, you´d do it like this:
$weapon = new Weapon();
$soldier = new Soldier();
$soldier->setWeapon($weapon);
$soldier->fight();
Allright, that was a lot of boilerplate code (bear with me, I am coming to explain what annotations are useful for pretty soon). What Dependency Injection frameworks can do for you is to abstract the creation such composed objects and inject all dependencies automatically, you simply do:
$soldier = Container::getInstance('Soldier');
$soldier->fight(); // ! weapon is already injected
Right, but the Container
has to know which dependencies a Soldier
class has. So, most of the common frameworks use XML as configuration format. Example configuration:
<class name="Soldier">
<!-- call setWeapon, inject new Weapon instance -->
<call method="setWeapon">
<argument name="Weapon" />
</call>
</class>
But what FLOW3 uses instead of XML is annotations directly in the PHP code in order to define these dependencies. In FLOW3, your Soldier
class would look like this (syntax only as an example):
class Soldier {
...
// ---> this
/**
* @inject $weapon Weapon
*/
public function setWeapon($weapon) {
$this->weapon = $weapon;
}
...
So, no XML required to mark the dependency of Soldier
to Weapon
for the DI container.
FLOW 3 uses these annotations also in the context of AOP, to mark methods which should be "weaved" (means injecting behaviour before or after a method).
As far as I am concerned, I am not too sure about the usefullness about these annotations. I dont know if it makes things easier or worse "hiding" this kind of dependencies and setup in PHP code instead of using a separeate file.
I worked e. g. in Spring.NET, NHibernate and with a DI framework (not FLOW3) in PHP both based on XML configuration files and cant say it was too difficult. Maintaing these setup files was ok, too.
But maybe a future project with FLOW3 proves the opposite and annotations are the real way to go.