Utilities

Version 8 (Kien La, 2010-07-18 12:15 PM)

1 2 Kien La
h2. Utilities
2 1
3 3 Kien La
*(#topic-list) "Delegators":/projects/main/wiki/Utilities#delegators
4 3 Kien La
* "Attribute Setters":/projects/main/wiki/Utilities#attribute-setters
5 6 Kien La
* "Attribute Getters":/projects/main/wiki/Utilities#attribute-getters
6 3 Kien La
* "Aliased attributes":/projects/main/wiki/Utilities#aliased-attributes
7 3 Kien La
* "Protected attributes":/projects/main/wiki/Utilities#protected-attributes
8 3 Kien La
* "Accessible attributes":/projects/main/wiki/Utilities#accessible-attributes
9 3 Kien La
* "Serialization":/projects/main/wiki/Utilities#serialization
10 7 Kien La
* "Automatic Timestamps":/projects/main/wiki/Utilities#automatic-timestamps
11 3 Kien La
12 1
ActiveRecord offers numerous ways to make your life easier by adding some interesting features to your models.
13 1
14 3 Kien La
h4(#delegators). Delegators
15 1
16 4 Kien La
This is similar to "attribute aliasing":/projects/main/wiki/Utilities#aliased-attributes, 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.
17 1
18 1
<pre class="code"><code class="php">
19 1
class Person extends ActiveRecord\Model {
20 1
  static $belongs_to = array(array('venue'),array('host'));
21 1
  static $delegate = array(
22 1
    array('name', 'state', 'to' => 'venue'),
23 1
    array('name', 'to' => 'host', 'prefix' => 'host'));
24 1
}
25 1
 
26 1
$person = Person::first();
27 1
$person->state     # same as calling $person->venue->state
28 1
$person->name      # same as calling $person->venue->name
29 1
$person->host_name # same as calling $person->host->name
30 1
</code></pre>
31 6 Kien La
32 3 Kien La
h4(#attribute-setters). Attribute setters
33 1
34 4 Kien La
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":/docs/ActiveRecord/UndefinedPropertyException will be thrown.
35 1
36 1
<pre class="code"><code class="php">
37 1
class User extends ActiveRecord\Model {
38 1
  static $setters = array('password','second_custom_setter');
39 1
 
40 1
  # A setter method must have set_ prepended to its name to qualify.
41 1
  # $this->encrypted_password is the actual attribute for this model.
42 1
  public function set_password($plaintext) {
43 1
    $this->encrypted_password = md5($plaintext);
44 1
  }
45 1
}
46 1
 
47 1
$user = new User;
48 1
$user->password = 'plaintext';  # will call $user->set_password('plaintext')
49 1
# if you did an echo $user->password you would get an UndefinedPropertyException
50 1
</code></pre>
51 1
52 4 Kien La
If you define a custom setter with the same name as an attribute then you will need to use "assign_attribute()":/docs/ActiveRecord/Model#methodassign_attribute to assign the value to the attribute. This is necessary due to the way "Model::__set()":/docs/ActiveRecord/Model#method__set works. For example, assume 'name' is a field on the table and we're defining a custom setter called 'name':
53 1
54 1
<pre class="code"><code class="php">
55 1
class User extends ActiveRecord\Model {
56 1
  static $setters = array('name');
57 1
 
58 1
  # INCORRECT:
59 1
  # function set_name($name) {
60 1
  #   $this->name = strtoupper($name);
61 1
  # }
62 1
63 1
  public function set_name($name) {
64 1
    $this->assign_attribute('name',strtoupper($name));
65 1
  }
66 1
}
67 1
 
68 1
$user = new User;
69 1
$user->name = 'bob';
70 1
echo $user->name; # => BOB
71 1
</code></pre>
72 6 Kien La
73 6 Kien La
h4(#attribute-getters). Attribute getters
74 6 Kien La
75 6 Kien La
Getters allow you to intercept attribute/property value retrieval on your models. They are defined in a similar manner to setters. See "Model::$getters":/docs/ActiveRecord/Model#var$getters for details.
76 1
 
77 3 Kien La
h4(#aliased-attributes). Aliased attributes
78 1
79 1
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.
80 1
81 1
<pre class="code"><code class="php">
82 1
class Person extends ActiveRecord\Model {
83 1
  static $alias_attribute = array(
84 1
    'first_name' => 'person_first_name',
85 1
    'last_name' => 'person_last_name');
86 1
}
87 1
 
88 1
$person = Person::first();
89 1
echo $person->person_first_name; # => Jax
90 1
91 1
$person->first_name = 'Tito';
92 1
echo $person->first_name; # => Tito
93 1
echo $person->person_first_name; # => Tito
94 1
</code></pre>
95 1
96 3 Kien La
h4(#protected-attributes). Protected attributes
97 1
98 4 Kien La
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":/projects/main/wiki/Utilities#accessible-attributes.
99 1
100 1
<pre class="code"><code class="php">
101 1
class User extends ActiveRecord\Model {
102 1
  static $attr_protected = array('admin');
103 1
}
104 1
 
105 1
$attributes = array('first_name' => 'Tito','admin' => 1);
106 1
$user = new User($attributes);
107 1
 
108 1
echo $user->first_name; # => Tito
109 1
echo $user->admin; # => null
110 1
# now no one can fake post values and make themselves an admin against your will!
111 1
</code></pre>
112 1
 
113 3 Kien La
h4(#accessible-attributes). Accessible attributes
114 1
115 4 Kien La
Whitelist of attributes that are checked from mass-assignment calls such as constructing a model or using "Model::update_attributes()":/docs/ActiveRecord/Model#methodupdate_attributes. This is the opposite of "protected attributes":/projects/main/wiki/Utilities#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.
116 1
117 1
<pre class="code"><code class="php">
118 1
class User extends ActiveRecord\Model {
119 1
  static $attr_accessible = array('first_name');
120 1
}
121 1
 
122 1
$attributes = array('first_name' => 'Tito','last_name' => 'J.','admin' => 1);
123 1
$user = new User($attributes);
124 1
 
125 1
echo $person->last_name; # => null
126 1
echo $person->admin; # => null
127 1
echo $person->first_name; # => Tito
128 1
# first_name is the only attribute that can be mass-assigned, so the other 2 are null
129 1
</code></pre>
130 1
 
131 1
h4(#serialization). Serialization
132 3 Kien La
133 1
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:
134 1
135 4 Kien La
*only*: a string or array of attributes to be included.
136 4 Kien La
*exclude*: a string or array of attributes to be excluded.
137 4 Kien La
*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
138 4 Kien La
*include*: a string or array of associated models to include in the final serialized product.
139 4 Kien La
*skip_instruct*: set to true to skip the <?xml ...?> declaration.
140 1
141 4 Kien La
Below only includes "Model::to_json()":/docs/ActiveRecord/Model#methodto_json examples; however, you can use all of the examples with "Model::to_xml()":/docs/ActiveRecord/Model#methodto_xml
142 4 Kien La
143 1
<pre class="code"><code class="php">
144 1
class User extends ActiveRecord\Model {
145 1
  static $has_many = array(array('orders'));
146 1
 
147 1
  public function name() {
148 1
    return $this->first_name .' '. $this->last_name;
149 1
  }
150 1
}
151 1
 
152 1
# assume these fields are on our `users` table:
153 1
# id, first_name, last_name, email, social_security, phone_number
154 1
155 1
$user = User::first();
156 1
 
157 1
# json should only contain id and email
158 1
$json = $user->to_json(array(
159 1
  'only' => array('id', 'email')
160 1
));
161 1
 
162 1
echo $json; # => {"id":1,"email":"none@email.com"}
163 1
164 1
# limit via exclusion (here we use a string, but an array can be passed)
165 1
$json = $user->to_json(array(
166 1
  'except' => 'social_security'
167 1
));
168 1
 
169 1
echo $json; # => {"id":1,"first_name":"George","last_name":"Bush",
170 1
            #     "email":"none@email.com","phone_number":"555-5555"}
171 1
172 1
# call $user->name() and the returned value will be in our json
173 1
$json = $user->to_json(array(
174 1
  'only' => array('email', 'name'),
175 1
  'methods' => 'name'
176 1
));
177 1
 
178 1
echo $json; # => {"name":"George Bush","email":"none@email.com"}
179 1
180 1
# call $user->name() and the returned value will be in our json
181 1
$json = $user->to_json(array(
182 1
  'only' => array('email', 'name'),
183 1
  'methods' => 'name'
184 1
));
185 1
 
186 1
# include the orders association
187 1
$json = $user->to_json(array(
188 1
  'include' => array('orders')
189 1
));
190 1
 
191 1
# you can nest includes .. here orders also has a payments association
192 1
$json = $user->to_json(array(
193 1
  'include' => array('orders' => array('except' => 'id', 'include' => 'payments')
194 1
));
195 1
</code></pre>
196 1
 
197 8 Kien La
DateTime fields are serialized to "ISO8601":http://www.php.net/manual/en/class.datetime.php#datetime.constants.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":/docs/ActiveRecord/DateTime#var$FORMATS
198 1
199 1
<pre class="code"><code class="php">
200 8 Kien La
ActiveRecord\Serialization::$DATETIME_FORMAT = 'Y-m-d';
201 8 Kien La
ActiveRecord\Serialization::$DATETIME_FORMAT = 'atom';
202 8 Kien La
ActiveRecord\Serialization::$DATETIME_FORMAT = 'long';
203 8 Kien La
ActiveRecord\Serialization::$DATETIME_FORMAT = \DateTime::RSS;
204 1
</code></pre>
205 7 Kien La
206 7 Kien La
h4(#automatic-timestamps). Automatic Timestamps
207 7 Kien La
208 7 Kien La
Models with fields named *created_at* and *updated_at* will have those fields automatically updated upon model creation and model updates.