我的公司有这样的模型,有方法 setOptions 从数组或 Zend_DB_Table_Row 创建对象
<?php
class Model_Company
{
protected $c_id;
protected $c_shortname;
protected $c_longname;
public function __constructor(array $options = null)
{
if(is_array($options)) {
$this->setOptions($options);
}
}
public function setOptions($data)
{
if($data instanceof Zend_Db_Table_Row_Abstract) {
$data = $data->toArray();
}
if(is_object($data)) {
$data = (array)$data;
}
if(!is_array($data)) {
throw new Exception('Initial data must be object or array');
}
$methods = get_class_methods($this);
foreach($data as $key => $value) {
$method = 'set'.ucfirst($key);
if(in_array($method, $methods)) {
$this->{'c_'.$key} = $value;
}
}
return $this;
}
我也有公司经理,其参数为模型和适配器,用于不同的 db/soap/rest
class Model_CompanyManager
{
private $_adapter;
public function __construct(Model_Company $model,$adapter)
{
$this->_adapter = $adapter;
$this->_model = $model;
return $this;
}
/**
* Save data
* @var Model_Company $data
*/
public function save(array $data)
{
$data = $this->_model->setOptions($data);
$this->_adapter->save($data);
}
}
和 DBTable 中的 DBTable
class Model_DbTable_Company extends Zend_Db_Table_Abstract
{
protected $_name = 'company';
protected $_id = 'c_id';
public function save(Model_Company $data)
{
try {
if(isset($data['c_id'])) {
$this->update($data, 'c_id = :c_id',array('c_id' => $data['c_id']));
} else {
$this->insert($data);
}
} catch (Zend_Db_Exception $e) {
throw new Exception($e->getMessage());
}
}
}
我如何插入数据库,因为模型属性受到保护,我不能做 (array)$data
$this->_companyManager = new Model_CompanyManager(new Model_Company,new Model_DbTable_Company);
$this->_companyManager->save($values);
我不会像这样创建带有字段名称的数组,如下所示:
$data = array(
'c_shortname' => $company->getShortname(),
'c_longname' => $company->getLongName(),
'c_description' => $company->getDescription(),
'c_salt' => $company->getSalt(),
'c_password' => $company->getPassword(),
'c_updated_at' => date('YmdHis')
);
因为当我要更改模型字段名称和其他内容时,我还必须记住要在这里更改...是否有简单的方法,模型可以保持一切并保持清洁