I have found myself doing this in my code to 'cache' the work done when instantiating my Zend_Db_Table
models:
if (Zend_Re开发者_如何学编程gistry::isRegistered('x_table')) {
$x_table = Zend_Registry::get('x_table');
} else {
$x_table = new Default_Model_DbTable_X;
Zend_Registry::set('x_table', $x_table);
}
It bothered me that this method isn't very DRY and it dawned on me today that a singleton pattern would probably be a better way to do this. Problem is, I've never written a singleton class. When I did some web searches, I found some offhand comments about Zend_Db_Table
singletons, but no real examples.
I already have meta-data caching configured.
- How do I make my
Zend_Db_Table
models singletons? - Are there pitfalls or downsides?
Edit: My reason for thinking a singleton was the answer is that I thought I could simply have the following calls in my code $x_table = new Default_Model_DbTable_X;
and the single instance would be returned if it existed. If this is possible, I would prefer that solution.
Why not just manage the DbTables in some sensible place? If there's no sensible place, create a DbTableManager class. Something like:
<?PHP
class DbTableMgr {
protected $_tables;
public function getTable($classname){
if ( empty($this->_tables[$name]) ){
//assuming some things about class names for the sake of brevity elsewhere...
$classname = 'Default_Model_DbTable_',ucfirst(strtolower($classname));
$this->_tables[$name] = new $classname;
}
return $this->_tables[$name];
}
}
Initialize the manager in your bootstrap and stick it in the registry.
Then:
<?PHP
//in a galaxy far, far, away
$dbtFoo = Zend_Registry::get('dbtMgr')->getTable('Foo');
So, you lazy-load the dbTable objects, and enforce a singleton-like behavior.
You could make the above static in various ways, if you wanted to.
精彩评论