我有基于TableGateway的课程:
namespace Model\Table;
class Meter extends AbstractTable
{
protected $tableName = 'meter';
public function __construct($adapter, $features = null)
{
parent::__construct($this->tableName, $adapter, $features);
}
}
这是我的工厂方法:
Table\Meter::class => function(ContainerInterface $container) {
$dbAdapter = $container->get(\Zend\Db\Adapter\Adapter::class);
$features = [
$container->get(MetadataFeature::class),
$container->get(RowGatewayFeature::class),
];
return new Table\Meter($dbAdapter, $features);
}
现在,如果我获取现有行,请尝试更改一些值,然后调用save()方法,一切正常:
$row = $this->select()->current();
$row->name = 'some new name';
$row->save();
但是,如果我需要创建新行怎么办?如何获取RowGateway对象,填充并保存?
答案 0 :(得分:0)
您将不得不创建RowGateway
的实例。而且,您需要为此引用DbAdapter。填充RowGateway
的新实例,然后保存它。
如果通过工厂向控制器提供DbAdapter:
namespace MyModule\Controller;
use Zend\Db\RowGateway\RowGateway;
use Zend\Mvc\Controller\AbstractActionController;
class MeterController extends AbstractActionController
{
/**
* @var \Zend\Db\Adapter\Adapter
*/
private $dbAdapter;
public function __construct(\Zend\Db\Adapter\Adapter $dbAdapter)
{
$this->dbAdapter = $dbAdapter;
}
public function insertAction()
{
$rowGateway = new RowGateway('id', 'meter', $this->dbAdapter);
$rowGateway->name = $this->params()->fromRoute('name');
$rowGateway->save();
}
}
另一种方法是将RowGateway本身作为原型提供给控制器,并在需要时将其克隆到那里:
namespace MyModule\Controller;
use Zend\Db\RowGateway\RowGateway;
use Zend\Mvc\Controller\AbstractActionController;
class MeterController extends AbstractActionController
{
/**
* @var \Zend\Db\RowGateway\RowGateway
*/
private $rowGatewayPrototype;
public function __construct(RowGateway $prototype)
{
$this->rowGatewayPrototype = $prototype;
}
public function insertAction()
{
$rowGateway = clone $this->rowGatewayPrototype;
$rowGateway->name = $this->params()->fromRoute('name');
$rowGateway->save();
}
}
工厂可能看起来像这样:
MeterController::class => function (ContainerInterface $container) {
$rowGateway = new RowGateway('id', 'meter', $container->get(\Zend\Db\Adapter\Adapter::class));
return new MeterController($rowGateway);
}