How to change Zend_Db_Table name within a Model to insert in multiple tables

前端 未结 3 1099
余生分开走
余生分开走 2021-01-03 09:37

Using Zend Framework, I\'ve created a Model to insert a record into a database. My question is, after $this->insert($data) how can I switch the active table

3条回答
  •  清酒与你
    2021-01-03 10:34

    Zend_Db_Table is a Table Data Gateway. It

    acts as a Gateway to a database table. One instance handles all the rows in the table.

    This means, you have one class per table. Your Model_DbTable_Foo represents the Foo table in your database and only this table. It should not do inserts on other tables. That's what you would use another table class for. The cleanest option would be to add another layer on top of your TDGs that knows how to handle inserts to multiple tables, e.g.

    class Model_Gateway_FooBar
    {
        protected $_tables;
    
        public function __construct(Zend_Db_Table_Abstract $foo, 
                                    Zend_Db_Table_Abstract $bar)
        {
            $this->_tables['foo'] = $foo;
            $this->_tables['bar'] = $bar;
        }
    
        public function addFoo($data)
        {
            $this->_tables['foo']->insert($data['foo']);
            // yaddayaddayadda
            $this->_tables['bar']->insert($data['bar']);
        }
    }
    

    However, it's your app and you can decide not to bother and simply create a new instance of the other class in the Foo class and do the insert from there, e.g.

    $otherTable = new Model_DbTable_Bar;
    $otherTable->insert($data);
    

    Another option would be to put the logic into the controller, but I cannot recommend it, because this is not the responsibility of a controller and generally controllers should be kept thin and models should be fat.

    On a sidenote, when you're doing multiple inserts, you might want to use transactions to make both inserts work as expected, e.g.

    $this->_tables['foo']->getAdapter()->beginTransaction();
    

    and then commit() or rollback() depending on the query outcome.

    Also note that as of ZF1.9, you can also create instances of Zend_Db_Table without having to define a concrete subclass first, e.g.

    $fooTable = new Zend_Db_Table('foo');
    

    See the chapter on Zend_Db_Table in the ZF Reference Guide.

提交回复
热议问题