问题
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