Zend_Db_Table_Row: Why do I have to use createRow()?

拜拜、爱过 提交于 2019-12-10 17:37:42

问题


I'm wondering why in Zend_Db you have to use the createRow method to get a new, empty Row object, rather than just instantiating the Row object directly.

For instance, if I've extended the default classes to create my own User table and row classes, then in order to create a new row object I always have to do the following to create a new Row object:

$userTable = new App_Table_User();
$userRow = $userTable->createRow();
$userRow->setName('bob');
$userRow->save();

But to me it makes more sense to be able to just say:

$userRow = new App_Row_User();
$userRow->setName('bob');
$userRow->save();

I understand that I can always build this functionality into my Row classes that extend Zend_Db_Table_Row_Abstract, but I'm wondering if there's a specific reason that the Zend Framework team didn't just make this the default?


回答1:


You can instantiate your Row class directly with new.

But the Row object needs to know what columns are valid for that row of data.

There is no magic to map a row's class name to its corresponding table class name. So the Row doesn't know by itself what table it belongs to. Therefore it can't guess how to write SQL to perform insert or update operations; it gets this metadata from the corresponding Zend_Db_Table object. You have to tell the Row which Table to use.

If you construct a row object with new, you must pass a config array to the constructor including either the table class name, or else an object instance of that table class.

$userRow = new App_Row_User( array('table' => 'App_Table_User') );

Or

$userTable = new App_Table_User();
$userRow = new App_Row_User( array('table' => $userTable) );

Without a valid table object or class name, instantiating a Row object with new will throw an exception.

Likewise, save() uses the table object, calling methods insert() or update(). Without a valid table object, the Row's save() method will throw an exception.



来源:https://stackoverflow.com/questions/7799776/zend-db-table-row-why-do-i-have-to-use-createrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!