Adding default database table prefixes in Zend Framework 1.9.x

Recently, I began working with Zend Framework 1.9.2 to restructure one of my web sites.  I learned how to create an extension of the Zend_Db_Table_Abstract from a great “Getting Started” tutorial, but I found myself rewriting the table prefix with each and every new table.  Below I explain one solution to this problem, but I am new to Zend Framework, so please feel free to recommend a better, more integrated way of doing this, if you know of anything.

Step 1:  application.ini

Place the following code in your /application/configs/application.ini file:

table_prefix = "webjawns_"

Step 2:  TPC_DB_Table_Abstract class

Create a new class in the library directory. For this example, we’ll use TPC_DB_Table_Abstract as the name, which will be stored in /library/TPC/DB/Table/Abstract.php.

class TPC_DB_Table_Abstract extends Zend_Db_Table_Abstract {
	protected function _setupTableName() {
		global $application;

		$prefix = $application->getOption('table_prefix');

		$this->_name = $prefix . $this->_name;

Step 3:  /application/Bootstrap.php

After that, you’ll want to make sure that the new Abstract.php file is referenced in your /application/Bootstrap.php file.

protected function _initAutoload() {
	$moduleLoader = new Zend_Application_Module_Autoloader( array(
		'namespace' => '',
		'basePath' => APPLICATION_PATH ) );
	$moduleLoader->addResourceType('', '../library/TPC', 'TPC');
	return $moduleLoader;

Step 4:  /application/models/DbTable/NewTable.php

To use the table prefix, we will basically be substituting Zend_Db_Table_Abstract with TPC_DB_Table_Abstract.  See the example below:

class Model_DbTable_NewTable extends TPC_DB_Table_Abstract {
	// Database name will be $prefix + $_name
	protected $_name = 'newtable';

This is just one way to create default table prefixes for each of your tables. I’m sure this isn’t the only way, and there may even be better, easier ways to do this. As an added bonus, we use the TPC_DB_Table_Abstract class to extend the Zend database functionality even further. If anyone else has any ideas about how to use default table prefixes (other than using a constant), please feel free to share them so we can all benefit.

2 thoughts on “Adding default database table prefixes in Zend Framework 1.9.x”

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>