Utilities

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