atk4 / book

4 stars 23 forks source link

Create article for object cloning #39

Open DarkSide666 opened 8 years ago

DarkSide666 commented 8 years ago

Issue by romaninsh Sunday Jun 08, 2014 at 13:52 GMT Originally opened as https://github.com/atk4/atk4/issues/551


Cloning Objects

When you use the PHP clone statement the whole object is duplicated into an independent variable.

$book_archive = clone $book;

$book_archive->addCondition('is_archive',true);
$book->addCondition('is_archive',false);

$this->add('Grid')->setModel('book');
$this->add('Grid')->setModel('book_archive');

This code will display two grids - one for regular books and another for archived. Because objects are cloned, adding conditions to one will not affect the other.

But be careful – there's a gotcha when you clone hooks.

To continue the example above, say you have a hook inside Model_Book to check a value before saving:

// In Model_Book

function init()
{
    parent::init();

    $this->addField('review');
    $this->hasOne('Author');

    $this->addHook('beforeSave', array($this,'check'));
}

function check($m)
{
    if (strlen($this['review']) < 100) {
        throw $this->exception('Review is too short');
    }
}

After cloning, $this will be referencing the wrong object! Saving our Model with $book_archive->save() will call $book->check(), and $this will validate the value of $book instead of $book_archive.

You can avoid this problem if you use the Model passed in as $m instead of $this inside a hook. In the above example, $m will point to $book_archive.

DarkSide666 commented 8 years ago

Comment by DarkSide666 Sunday Jun 08, 2014 at 22:11 GMT


Ouch, I never imagined that it happens like this. This is definitely one aspect to keep in mind while cloning objects!

romaninsh commented 8 years ago

ATK is not entirely clone-safe. I know that DSQL certainly is clone-safe, the Model - I'm not entirely sure, but Agile data will surely be clone-safe. The rest of the views - I'm not even sure. Probably you can create an article on your blog about usage of Clone.