Utilities

ActiveRecord offers numerous ways to make your life easier by adding some interesting features to your models.

Delegators

This is similar to attribute aliasing, except that it works via your associations. You can alias an attribute on your model to use a particular attribute on an association. Let's take a look.

 1 class Person extends ActiveRecord\Model {
 2   static $belongs_to = array(array('venue'),array('host'));
 3   static $delegate = array(
 4     array('name', 'state', 'to' => 'venue'),
 5     array('name', 'to' => 'host', 'prefix' => 'host'));
 6 }
 7 
 8 $person = Person::first();
 9 $person->state     # same as calling $person->venue->state
10 $person->name      # same as calling $person->venue->name
11 $person->host_name # same as calling $person->host->name

Attribute setters

Setters allow you to define custom methods for assigning a value to one of your attributes. This means you can intercept the assign process and filter/modify the data to your needs. This is helpful in a situation such as encrypting user passwords. Normally, you define a setter which does not carry the same name as your attribute, but you can set your attribute inside of the method. In the example below, $user->password is a virtual attribute: if you try to read/access the attribute instead of assign, an UndefinedPropertyException will be thrown.

 1 class User extends ActiveRecord\Model {
 2 
 3   # A setter method must have set_ prepended to its name to qualify.
 4   # $this->encrypted_password is the actual attribute for this model.
 5   public function set_password($plaintext) {
 6     $this->encrypted_password = md5($plaintext);
 7   }
 8 }
 9 
10 $user = new User;
11 $user->password = 'plaintext';  # will call $user->set_password('plaintext')
12 # if you did an echo $user->password you would get an UndefinedPropertyException

If you define a custom setter with the same name as an attribute then you will need to use assign_attribute() to assign the value to the attribute. This is necessary due to the way Model::__set() works. For example, assume 'name' is a field on the table and we're defining a custom setter called 'name':

 1 class User extends ActiveRecord\Model {
 2 
 3   # INCORRECT:
 4   # function set_name($name) {
 5   #   $this->name = strtoupper($name);
 6   # }
 7 
 8   public function set_name($name) {
 9     $this->assign_attribute('name',strtoupper($name));
10   }
11 }
12 
13 $user = new User;
14 $user->name = 'bob';
15 echo $user->name; # => BOB

Attribute getters

Getters allow you to intercept attribute/property value retrieval on your models. They are defined in a similar manner to setters. See Model::__get for details.

Aliased attributes

This option is fairly straight-forward. An aliased attribute allows you to set/get the attribute via a different name. This comes in handy when you have terrible field names like field_one, field_two, or for legacy tables. In this example, the alias first_name is created to reference the existing field person_first_name.

 1 class Person extends ActiveRecord\Model {
 2   static $alias_attribute = array(
 3     'first_name' => 'person_first_name',
 4     'last_name' => 'person_last_name');
 5 }
 6 
 7 $person = Person::first();
 8 echo $person->person_first_name; # => Jax
 9 
10 $person->first_name = 'Tito';
11 echo $person->first_name; # => Tito
12 echo $person->person_first_name; # => Tito

Protected attributes

Blacklist of attributes that cannot be mass-assigned. Protecting these attributes allows you to avoid security problems where a malicious user may try to create additional post values. This is the opposite of accessible attributes.

 1 class User extends ActiveRecord\Model {
 2   static $attr_protected = array('admin');
 3 }
 4 
 5 $attributes = array('first_name' => 'Tito','admin' => 1);
 6 $user = new User($attributes);
 7 
 8 echo $user->first_name; # => Tito
 9 echo $user->admin; # => null
10 # now no one can fake post values and make themselves an admin against your will!

Accessible attributes

Whitelist of attributes that are checked from mass-assignment calls such as constructing a model or using Model::update_attributes(). This is the opposite of protected attributes. Accessible attributes can also be used as a security measure against fake post values, except that it is often more pragmatic because it is a whitelist approach.

 1 class User extends ActiveRecord\Model {
 2   static $attr_accessible = array('first_name');
 3 }
 4 
 5 $attributes = array('first_name' => 'Tito','last_name' => 'J.','admin' => 1);
 6 $user = new User($attributes);
 7 
 8 echo $person->last_name; # => null
 9 echo $person->admin; # => null
10 echo $person->first_name; # => Tito
11 # first_name is the only attribute that can be mass-assigned, so the other 2 are null

Serialization

This is not the normal kind of PHP serialization you are used to. This will not serialize your entire object; however, it will serialize the attributes of your model to either an xml or a json representation. An options array can take the following parameters:

only: a string or array of attributes to be included.
except: a string or array of attributes to be excluded.
methods: a string or array of methods to invoke. The method's name will be used as a key for the final attributes array along with the method's returned value
include: a string or array of associated models to include in the final serialized product.
skip_instruct: set to true to skip the declaration.

Below only includes Model::to_json() examples; however, you can use all of the examples with Model::to_xml()

 1 class User extends ActiveRecord\Model {
 2   static $has_many = array(array('orders'));
 3 
 4   public function name() {
 5     return $this->first_name .' '. $this->last_name;
 6   }
 7 }
 8 
 9 # assume these fields are on our `users` table:
10 # id, first_name, last_name, email, social_security, phone_number
11 
12 $user = User::first();
13 
14 # json should only contain id and email
15 $json = $user->to_json(array(
16   'only' => array('id', 'email')
17 ));
18 
19 echo $json; # => {"id":1,"email":"[email protected]"}
20 
21 # limit via exclusion (here we use a string, but an array can be passed)
22 $json = $user->to_json(array(
23   'except' => 'social_security'
24 ));
25 
26 echo $json; # => {"id":1,"first_name":"George","last_name":"Bush",
27             #     "email":"[email protected]","phone_number":"555-5555"}
28 
29 # call $user->name() and the returned value will be in our json
30 $json = $user->to_json(array(
31   'only' => array('email', 'name'),
32   'methods' => 'name'
33 ));
34 
35 echo $json; # => {"name":"George Bush","email":"[email protected]"}
36 
37 # include the orders association
38 $json = $user->to_json(array(
39   'include' => array('orders')
40 ));
41 
42 # you can nest includes .. here orders also has a payments association
43 $json = $user->to_json(array(
44   'include' => array('orders' => array('except' => 'id', 'include' => 'payments')
45 ));

DateTime fields are serialized to ISO8601 format by default. This format can be changed by setting ActiveRecord\Serialization::$DATETIME_FORMAT. You can use a raw formatter or any of the pre-defined formats defined in DateTime::$FORMAT

1 ActiveRecord\Serialization::$DATETIME_FORMAT = 'Y-m-d';
2 ActiveRecord\Serialization::$DATETIME_FORMAT = 'atom';
3 ActiveRecord\Serialization::$DATETIME_FORMAT = 'long';
4 ActiveRecord\Serialization::$DATETIME_FORMAT = \DateTime::RSS;

Automatic Timestamps

Models with fields named created_at and updated_at will have those fields automatically updated upon model creation and model updates.

Also available in: HTML TXT