gpt4 book ai didi

zend-framework2 - 如何在 Zend Framework 2 中将 db 适配器设置为 Validator RecordExists

转载 作者:行者123 更新时间:2023-12-01 09:32:22 26 4
gpt4 key购买 nike

我正在尝试将验证器 RecordExists 添加到我的表单中,但出现错误“没有 db 适配器存在”。如何将 db 适配器设置为此验证器?我使用骨架应用程序中的示例,我正在尝试做这样的事情(是的,我知道 $dbAdapter 是未定义的 :) 我正在寻找如何将此变量更改为 db 适配器资源的解决方案):

namespace Album\Model;

use Zend\InputFilter\Factory as InputFactory; // <-- Add this import
use Zend\InputFilter\InputFilter; // <-- Add this import
use Zend\InputFilter\InputFilterAwareInterface; // <-- Add this import
use Zend\InputFilter\InputFilterInterface; // <-- Add this import

class Album implements InputFilterAwareInterface
{
public $id;
public $artist;
public $title;
protected $inputFilter; // <-- Add this variable

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;
}

// Add content to this method:
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}

public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();

$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
'validators' => array(
array(
'name' => 'Db\RecordExists',
'options' => array(
'table' => 'album',
'field' => 'title',
'adapter' => $dbAdapter
),
),
),
)));

$this->inputFilter = $inputFilter;
}

return $this->inputFilter;
}

}

最佳答案

您可以创建“专辑/模型/专辑”工厂并将 dbAdapter 注入(inject)专辑模型。

'service_manager' => array(
'factories' => array(
'Application/Model/Album' => function($sm){
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$album = new \Application\Model\Album();
$album->setDbAdapter($dbAdapter);
return $album;
},
),
),

现在我们必须实现 setDbAdapter 和 getDbAdapter 方法:

namespace Application\Model;

class Album
{
public $id;
public $artist;
public $title;

private $_dbAdapter;

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;
}

public function setDbAdapter($dbAdapter) {
$this->_dbAdapter = $dbAdapter;
}

public function getDbAdapter() {
return $this->_dbAdapter;
}
}

您可以通过调用 $this->getDbAdapter();

在输入过滤器中获取 dbAdapter

记得通过 ServiceLocator 在 Controller 中获取专辑模型,否则 dbAdapter 在您的模型中将不可用。

$album = $this->getServiceLocator()->get('Application/Model/Album');

关于zend-framework2 - 如何在 Zend Framework 2 中将 db 适配器设置为 Validator RecordExists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13818525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com