Welcome Guest, Not a member yet? Register   Sign In
DataMapper - How to execute method immediately after GET
#1

[eluser]Genki1[/eluser]
How to run a method immediately after an object is GET?

I see the "get_rules" feature but it seems to apply to a single field whereas I want to manipulate several fields at once.

For example, immediately after GETting a table record, I want to run my_custom_function() which operates on various fields and updates some class properties, like this:

Code:
function _my_custom_function()
{
   $this->var_one = $this->field_a + 1;
   $this->var_two = $this->field_b + 1;
   $this->var_three = $this->field_c + 1;
}

Should I create a get_rule for any random field (say, the ID field) and then call my function, like this?

Code:
var $validation = array(
    'id' => array(
        'label' => 'ID',
        'rules' => array(),
        'get_rules' => array('my_custom_function')
    )
);


Reference:
get_rules: http://datamapper.wanwizard.eu/pages/getrules.html
#2

[eluser]WanWizard[/eluser]
The proper way is to overload the get() method. You could do it this way, it's just not that clean or transparent.
#3

[eluser]Genki1[/eluser]
Thanks for that info. So, I've been researching this but don't understand how to overload the get() method. My mind is now, well, overloaded :-)

Would you kindly provide an example of how to accomplish this?
#4

[eluser]WanWizard[/eluser]
In your model:
Code:
public function get($limit = NULL, $offset = NULL)
{
    // call the original method
    parent::get($limit, $offset);

    // now do your thing here

    // for method chaining
    return $this;
}

Note that get() can return multiple objects, so if you want to modify or add something, do not modify $this, but iterate over $this->all and modify those objects.

The first object in the "all" array is a reference to $this, so by doing this you automatically modify the object itself as well...
#5

[eluser]Genki1[/eluser]
Thank you, as always, WanWizard!




Theme © iAndrew 2016 - Forum software by © MyBB