Zend framework2 zend framework 2从实体获取表instance
我是zf2的新手,在适应它的工作方式方面遇到了一些困难 基本上,我试图从实体中获取表处理程序的实例 在这个例子中(我们有一个Zend framework2 zend framework 2从实体获取表instance,zend-framework2,Zend Framework2,我是zf2的新手,在适应它的工作方式方面遇到了一些困难 基本上,我试图从实体中获取表处理程序的实例 在这个例子中(我们有一个 namespace Album\Model; class Album { public $id; public $artist; public $title; public function exchangeArray($data) { $this->id = (isset($data['id'])) ? $data['i
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();
实际上,您根本不需要这个
getAlbumTable()
函数。这样做主要是为了稍微清理一下代码,但坦率地说:根本不需要。您可以自己设置访问ServiceManager的操作:
public function overviewAction() { // very minified
$table = $this->getServiceLocator()->get('Album\Model\AlbumTable');
return array('albums' => $table->fetchAll());
}
将其分离的优点主要是为了在一个请求之间转发到另一个操作。在这种情况下,ServiceLocator
不会被第二次调用
您的方法会使代码变得有点模糊。因为您的模型和映射器之间没有明确的分离。相册
-模型应该只是一个数据对象