nightingale2k1
nightingale2k1

Reputation: 10335

zend framework: how to create trigger "before/after" insert/update

I am looking for a method that will be called before/after insert() or update() in Zend_DB? I am don't want to relly on database trigger for this ... could you help me ? thank you !!!

Upvotes: 2

Views: 2249

Answers (1)

Treffynnon
Treffynnon

Reputation: 21563

Just override the insert() and update() methods in your Table class.

For example:

<?php
class ObjectNameTable extends Zend_Db_Table_Abstract {
    protected $_name = 'table_name'; // table name
    protected $_primary = 'id';

    public function insert(array $data) {
        $data['added'] = date('Y-m-d H:i:s');
        return parent::insert($data);
    }

    public function update(array $data, $where) {
        $data['updated'] = date('Y-m-d H:i:s');
        return parent::update($data, $where);
    }
}

If you want to do it for all your table objects then you could have a base class that they all extend such as:

<?php
class BaseTable extends Zend_Db_Table_Abstract {
    public function insert(array $data) {
        $data['added'] = date('Y-m-d H:i:s');
        return parent::insert($data);
    }

    public function update(array $data, $where) {
        $data['updated'] = date('Y-m-d H:i:s');
        return parent::update($data, $where);
    }
}

And then a class to use it:

<?php
class ObjectNameTable extends BaseTable {
    protected $_name = 'table_name'; // table name
    protected $_primary = 'id';
}

Upvotes: 4

Related Questions