Adding Functionality
- Static methods that apply to the Model
- Instance methods that apply to each Entity (Document or Record)
As a rule of thumb, all static methods work with a collection of objects on the database, while non-static methods are tied to one single document/record. Consider the following example:
The method is static because it iterates over a bunch of entities in your database and returns the first entry where the author
equals foobar
. The result you get is an instance of a Post
so all subsequent methods on it are non-static. The second line in the example sets the title
and the third line saves it back to the database. This concept feels natural and also has the benefit of instantly knowing on what kind of dataset you’re operating.
One simple example is if you have a bit of data that is specific to a model’s domain, and you want to make that data available to controllers using those models.
namespace app\models;
class Users extends \lithium\data\Model {
protected static $_roles = ['admin', 'friend', 'stranger'];
public static function roles() {
return static::$_roles;
}
}
Because this method is accessed statically, it behaves as you’d expect:
namespace app\models;
public function fullName($entity) {
return $entity->firstName . ' ' . $entity->middleInitial . '. ' . $entity->lastName;
}
}
If you want to add additional parameters, do so after you’ve specified the entity as the first:
Once this is done, use it wherever you’ve got access to a Users
model instance:
$firstUser = Users::first();