Managing Your Data With DatabaseObject
Setters, Getters And Checkers
For every different column in your table, it is possible to define three separate callback functions.
Setters
A setter callback is used to manipulate a value or perform some action when someone tries to set a value, using the setProperty() method.
For example, let’s say when a user’s username is set, internally you want to store some extra characters with that username. So let’s say a person specified fred as their username, but you wanted to store it as fred@phpriot instead, you could create a setter which did this for you.
Setters have the function name of _setCOLUMNNAME. They are automatically called when that field is set. A setter takes the value the user tried to set, and returns the new value. So to implement our example from the previous paragraph, the setter would look like:
class User extends DatabaseObject { /* ... other code ... */ function _setUsername($username) { return $username . '@phpriot'; } } $user = new User($db); $user->setProperty('username', 'fred');
If a username contains an underscore, such as first_name, the setter would be called _setFirst_name().
Additionally, the passed in value must pass the corresponding checker method if one exists (see further below).
Getters
A getter callback is used to manipulate a value someone is trying to fetch from the active record, using the getProperty() method. So as with the setter example, if you store the username as fred@phpriot, you might want to only return the fred part to the user, as that is what they think their username is. Getters work opposite to setters, so the stored value is passed in, and the value to send back is what is returned. Additionally, getter methods are prefixed with _get.
class User extends DatabaseObject { /* ... other code ... */ function _getUsername($username) { return preg_replace('/@phpriot$/', '', $username); } } $user = new User($db); echo $user->getProperty('username');
Checkers
A checker callback is used to ensure the passed in value is valid. It is called either when the user called setProperty() or checkProperty() on the respective field.
Checkers return true if the value is deemed to valid, or false if not.
Going back to our user example, you might want to ensure the user enters a valid email address, which you could do with the following:
class User extends DatabaseObject { /* ... other code ... */ function _checkEmail($email) { return preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i', $email); } } $user = new User($db); if (!$user->checkProperty('email', 'fred@example.com')) { echo 'Invalid email address'; }




