Utilities

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