Polski English

Yii Addendum - annotations for Yii

Describing Yii components redefined

Goal of this extension is to provide additional metadata for any class, their properties or methods. It's based on annotations, so adding this metadata is as easy as adding doc comments. Metadata for each class property is condensed in one place, just where it should be - right above property declaration. This makes defining and inspecting models extremely efficient.

This extension uses php addendum as annotations parsing engine.

Key features

  • Easy add metadata
  • Lightweight container
  • Extendable
  • Netbeans completition support

Why?

Let's take at example Yii CActiveRecord models. The most simple user class, defined by only id and name.

class User extends CActiveRecord
{
    public $id; public $name;
}
There are fields, representing columns on database. For each field there is at least few additional data defined: Label, Relations, Validators. It is all returned by predefined methods, like attribute labels:

class User extends CActiveRecord
{
    public $id; public $name; public function attributeLabels()
{
     return array( 'name' => 'First name' );
} public function rules() { return array( array('id, name', 'required') ); } public function tableName() { return 'user_table'; } // More class-enchancing methods
}

Now, it is very easy to define built in attributes, but there are caveauts which will arise - specially on larger projects.

  1. In above example name attribute is mentioned in 3 different places
  2. There is no easy way to add custom attribute
  3. When adding new class field, you have to add references to it in many places

Solution for this came with annotations, subject not very popular in PHP, mostly because it is not a language part. But with good design it is possible to use annotations efficiently from both coding convenience and application performance. Now, consider above user class defined with annotations:

/**
 * @TableName('user_table')
 */
class User extends CActiveRecord
{ /** * @RequiredValidator */
    public $id; /** * @RequiredValidator * @Label('First name') */ public $name; }
In example above, every additional information (meta data) is near attribute defining it. Even in this simple example this obviously looks cleaner, there also less code lines.