Re: DataObject & calculated fields
| From: | Ian Eure | Date: | Fri, 23 Jan 2004 21:30:18 +0000 |
| Subject: | Re: DataObject & calculated fields | ||
| References: | 1 | Groups: | php.pear.dev |
| Request: | Send a blank email to pear-dev+get-25240@lists.php.net to get a copy of this message | ||
On Friday 23 January 2004 01:02 pm, Norbert Mocsnik wrote:
> Hi again,
>
> Yesterday I was thinkin about DataObject and calculated fields..
> I know calcfields from Delphi and find them really useful. The main idea
> is very simple: let the developer be able to create new fields in any
> table, from code. The value of this field is calculated on-the-fly after
> fetching a record. Imagine a simple scenario about user profiles:
> users
> -----
> userid
> first_name
> last_name
> ..
>
> You can create a (virtual) field from code called full_name which
> contains the concatenation of first and last name fields. I did the
> following:
>
Sounds like a good place to use stored procedures.
> 1. added a new function to the DataObject core:
> function _calcFields() {
> if (method_exists($this, 'calcFields')) {
> $this->calcFields();
> }
> }
>
> 2. at the end of fetch() (before "return true;") I call:
> $this->_calcFields();
> so my function will be called every time after fetching a record.
> * Note: I'm not sure about where to place this call. I'm not sure this
> will be called after every fetch because there are fetches when the
> fetch() function itself won't be called. It would be nice if someone
> could help me to find the points to call it from.
>
I have something similar, DataObject_Filter[1]. It's got more features, as it
allows you to have a function triggered after fetch, and before insert and
update. Handlers are field-specific, and can be stacked. So, for example, I
use it to strip backslashes off strings stored in the database.
I have a function called _filterStripSlashes() which does this, and in my
DataObject's constructor I call:
$this->addFilter('fetch', 'stringField', array(get_class($this),
'_filterStripSlashes'));
And that registers the filter, and your field is automagically processed. I
also use it for transparent encryption of passwords, like so:
function _filterMD5Password(&$object, $field)
{
$object->$field = md5($object->$field);
}
and in the constructor:
$this->addFilter('insert', 'password', array(get_class($this),
'_filterMD5Password'));
$this->addFilter('update', 'password', array(get_class($this),
'_filterMD5Password'));
So when you insert or update, you just set the plaintext password in the
DataObject, and it's encrypted before it goes into the database.
[1]: http://www.websprockets.com/~ieure/PEAR/