我使用的是zf2 2的tableGateway,我不确定它会导致什么设计。
下面是如何使用ZF2的tableGateway进行插入(此从医生那里)的典型示例:
public function saveAlbum(Album $album)
{
$data = array(
'artist' => $album->artist,
'title' => $album->title,
);
$id = (int)$album->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAlbum($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}但是定义$data数组似乎是多余的,因为我已经有一个相册类,如下所示:
class Album
{
public $id;
public $artist;
public $title;
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->artist = (isset($data['artist'])) ? $data['artist'] : null;
$this->title = (isset($data['title'])) ? $data['title'] : null;
}
}在我自己的项目中,我有一个具有大约25个属性的模型(一个包含25列的表)。定义具有25个属性的类以及在实现$data的类的方法中编写一个tableGateway数组,对于这些属性中的每个属性都有一个元素,这似乎是多余的。我是不是遗漏了什么?
发布于 2014-04-23 19:39:11
你可能想看看我的QuickStart 101教程。
基本上你可以:
saveAlbum(Album $albumObject)
{
$hydrator = new ClassMethods(false);
$albumArray = $hydrator->extract($albumObject);
// v-- not too sure if that one-liner works; normal if() in case it doesn't
isset($albumArray['id']) ? unset($albumArray['id']) :;
// insert into tablegateway
}发布于 2014-04-24 13:42:21
另一种方法是使用RowGateway http://framework.zend.com/manual/2.3/en/modules/zend.db.row-gateway.html
简单地说,我将从\Zend\Db\RowGateway\AbstractRowGateway类扩展相册类。
<?php
namespace Module\Model;
use Zend\Db\RowGateway\AbstractRowGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
class Album extends AbstractRowGateway
{
protected $primaryKeyColumn = array( 'id' );
protected $table = 'album';
public function __construct( Adapter $adapter )
{
$this->sql = new Sql( $adapter, $this->table );
$this->initialize();
}
}然后你就可以这样做了
$album->title = "Some title";
$album->save();或
$album->populate( $dataArray )->save();https://stackoverflow.com/questions/23252934
复制相似问题