开发者

Custom logic for updating a row

开发者 https://www.devze.com 2023-01-24 02:30 出处:网络
I have this table class: class Songs extends Zend_Db_Table_Abstract { protected $_name = \'songs\'; protected $_primary = \'song_id\';

I have this table class:

class Songs extends Zend_Db_Table_Abstract
{
    protected $_name = 'songs';
    protected $_primary = 'song_id';
    protected $_rowClass = 'Song';
}

And a class that extends the class above with some custom logic.

class Song extends Zend_Db_Table_Row_Abstract
{
    protected function _insert()
    {
        print_r($this);
        // $this does exist
    }

    protected function _update()
    {
        print_r($this);
        //$this does not existing when updating a row, why not?
    }
}

My problem is that when I'm inserting a new row I can use $this in my custom logic.

$row->save(); // $this exists in _insert()

But it doesn't exist when I'm trying to update a row.

$myRow->update($data, $where); // $this does not exists in _update()

Why does $this not exist when I want to do some开发者_如何学Go custom logic before updating a row?


To update a row, you don't use:

$myRow->update($data, $where); 

You use:

$myRow->save(); 

But trying to use update() on a row object should throw an exception.

So I'm guessing you're actually calling the update() function on the table object, and not the row object.

$songs = new Songs();
//...
$songs->update($data, $where);

At that point the row object is never even used, the query is simply generated from the $data array and the $where clause.

If you want to use the custom _update() method you would need to do something like:

$songs = new Songs();
$song = $songs->find($id)
//change some data
$song->save();

Of course is also perfectly valid to add custom logic at the table level, and should be noted while calling an update or insert from the table object does not use the row object, calling save() on the row object proxies the table object.

For example, from the Zend_Db_Table_Row _doInsert() function:

$this->_insert();
//...
$primaryKey = $this->_getTable()->insert($data);

So if you have custom logic that you want to use every time you update a row (whether you update from the table object or the row object), it should be put into the table object.

From the Zend_Db_Table_Row docs:

If you need to do custom logic in a specific table, and the custom logic must occur for every operation on that table, it may make more sense to implement your custom code in the insert(), update() and delete() methods of your Table class. However, sometimes it may be necessary to do custom logic in the Row class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号