Pre and post database operations with Zend Framework using Zend_Db_Table_Row

Hi all.

Here I am again.

Today I have a quick tip for beginners using Zend Framework.

Do not insert pre and post code (for database) in your Controller. The Zend_Db_Table_Row is for that.

Lets create our DatabaseTable class for Posts:

/**  
* Located in .../models/DbTable/Posts.php  
*/  
class Posts extends Zend\_Db\_Table_Abstract  
{
    protected $_primary = 'id';  
    protected $_name = 'posts';  
    protected $_rowClass = 'Post'; // here we linked the Post class above  
}

Now, we have to create Post class using Zend_Db_Table_Row:

/**  
* Located in .../models/Post.php  
*/  
class Post extends Zend\_Db\_Table\_Row\_Abstract  
{

    protected function _insert() // before insert  
    {  
        $this->postDate = date('c');  
        // ...  
    }

    protected function _postInsert() // after insert  
    {  
        // send mail, for example  
    }

    protected function _update() // before update  
    {  
        // I can access a database field  
        // for example -> if the user changed the title using a form  
        // I can access the old and new title...  
        $oldTitle = $this->_cleanData['title']; // what I have in the database  
        $newTitle = $this->title; // sent by user  
    }

    // we also have

    protected function _postUpdate(); // post update  
    protected function _delete(); // before delete  
    protected function _postDelete(); // after delete  
}

And… in your controller:

$postsDT = new Posts();  
$newRow = $postsDT->createRow($form->getValues());  
$newRow->save(); // add the postDate field using Zend\_Db\_Table_Row -> Post.php

That’s all. Thanks!

Published by

Junior Grossi

senior software engineer & stutterer conference speaker. happy husband & dad. maintains Corcel PHP, elePHPant.me and PHPMG. Engineering Manager @ Paddle

Leave a Reply

Your email address will not be published. Required fields are marked *