Php – How to create a new row without the table class in the Zend Framework

oopPHPzend-db-tablezend-framework

I understand that you can have class Users extends Zend_Db_Table_Abstract and class User extends Zend_Db_Table_Row_Abstract, setting the $_rowClass property of Users to User.

To create and save a new row, I only know how to do the following:

$users = new Users()
$user = $users->createRow();
$user->name = 'name';
$user->save();

Can you tell me how I can do the follwing instead?

$user = new User();
$user->name = 'name';
$user->save();

As a side note, I'm also considering trying to use the following syntax to get a specific row:

$user = new User($userID);

Given however that this isn't trying to create a new User but to get an existing user, I think the following syntax may be more readable – what do you think?

$users = new Users();
$user = $users->fetchRow($userID);

Best Answer

Here's how to construct a new row instance without a Table object:

class User extends Zend_Db_Table_Row_Abstract
{
  protected $_tableClass = "Users";
}

$user = new User();
$user->name = "name";
$user->save();  // performs an INSERT

Here's how to construct a row instance for a given row in the database, without a Table object:

class User extends Zend_Db_Table_Row_Abstract
{
  protected $_tableClass = "Users";

  public function __construct(array $config = array())
  {
    if (isset($config["key"]) {
      $table = $this->_getTableFromString($this->_tableClass);
      $rowset = call_user_func_array(array($table, "find"), (array) $config["key"]);
      $row = $rowset->current();
      if ($row != false) {
        $config["data"] = $row->toArray();
        $config["stored"] = true;
      }
    }
    parent::__construct($config);
  }
}

$user = new User(array("key"=>$userid));
$user->name = "name";
$user->save(); // performs an UPDATE

NB: these code samples are not tested, I'll leave that to you.

Related Topic