Zend Framework - Singleton Database Table

I found myself doing this in my code to "cache" the work that is done when instantiating my models Zend_Db_Table:

if (Zend_Registry::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);
}

I was worried that this method is not very dry, and today it became clear to me that a singleton pattern would probably be the best way to do this. The problem is that I never wrote a single class. When I did some search queries on the Internet, I found some comments in the comments about singles Zend_Db_Table, but no real examples.

I already have metadata caching configured.

  • How to make my singleton models Zend_Db_Table?
  • Are there any pitfalls or flaws?

:. , , $x_table = new Default_Model_DbTable_X;, , . , .

+3
1

DbTables - ? , DbTableManager. - :

<?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];  
  }
}

.

:

<?PHP
//in a galaxy far, far, away
$dbtFoo = Zend_Registry::get('dbtMgr')->getTable('Foo');

, lazy-load dbTable .

, .

+3

Source: https://habr.com/ru/post/1741173/


All Articles