我是 zf2 的新手,在适应它的工作方式时遇到了一些困难。
基本上我正在尝试从实体中获取表处理程序的实例
在这个例子中(我们有一个
namespace Album\Model;
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;
}
}
还有一张桌子逍遥游
namespace Album\Model;
use Zend\Db\TableGateway\TableGateway;
class AlbumTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getAlbum($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
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');
}
}
}
public function deleteAlbum($id)
{
$this->tableGateway->delete(array('id' => $id));
}
}
在使用 ServiceManager 配置表网关并注入到 AlbumTable 之后,我们可以将此功能放在控制器中
public function getAlbumTable()
{
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
}
所以我们可以做类似的事情
public function indexAction(){
$albums = $this->getAlbumTable()->fetchAll();
return array('albums' => $albums);
}
我发现这非常多余,因为这样如果我们有另一个控制器,我们必须再次重新声明 getAlbumTable 函数
我的问题是有没有办法从实体专辑中获取表的实例
就像是
$album = new Album();
$album->getTable()->findAll();