ZF2 文档在 defult services documentation 上说以下内容;
InputFilterManager, mapping to Zend\Mvc\Service\InputFilterManagerFactory. This creates and returns an instance of Zend\InputFilter\InputFilterPluginManager, which can be used to manage and persist input filter instances.
我有一个自定义的 zf2 inputfilter 类,我正在 init() 方法中添加过滤器和验证器,如下所示;
namespace Application\Filter;
use Zend\InputFilter\InputFilter;
class GlassFilter extends InputFilter
{
public function init()
{
$this->add(array(
'name' => 'glassname',
'required' => true,
'filters' => array(
array('name' => 'StringToUpper'),
),
'validators' => array(
array( 'name' => 'StringLength', 'options' => array('min' => 3),
),
));
}
我还向我的 module.config.php 添加了以下键
'filters' => array(
'invokables' => array(
'glassfilter' => '\Application\Filter\GlassFilter',
),
),
我的问题是,如何使用 InputFilterManager 构建我的 GlassFilter?这是正确的方法吗?我找到了 this thread但我想了解自定义 InputFilters 和 InputFilterManager 之间的关系。
最佳答案
好吧,在花了 3 个该死的小时后(多亏了令人难以置信的(!)文档)我想通了。我正在写我的解决方案作为答案,希望它能帮助其他想要编写自定义输入过滤器的人。
- 您应该在
module.config.php
中通过 input_filters 顶部键注册您的自定义输入过滤器,而不是 filter、filters、filter_manger、filtermanager 等。 - 在编写您自己的
GlassFilter
时扩展默认Zend\InputFilter\InputFilter
。 - 在
GlassFilter
的init()
方法中编写过滤器,而不是在__constructor()
中。构建完成后自动调用。 - 然后通过
inputfiltermanager
获取它,而不是直接通过servicemanager
获取它。
配置示例:
'input_filters' => array(
'invokables' => array(
'glassfilter' => '\Application\Filter\GlassFilter',
),
),
使用示例:
$glassfilter = $serviceLocator->get('InputFilterManager')->get('glassfilter');
关于php - 如何使用 InputFilterManager 在 Zf2 中构建自定义 InputFilters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16606109/