zend框架在模型中验证数据,而不是在表单中 [英] zend framework validate data in model instead in the form

查看:130
本文介绍了zend框架在模型中验证数据,而不是在表单中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Zend Framework 2.在我的应用程序中,编辑数据库中的数据可能是编译html表单或发送http post请求(我的服务器是作为web服务实现的)。在这第二种情况下,表单不被渲染。
问题:
如果我在服务器收到不是来自表单而是来自通用http post请求(如移动应用程序)发送的post请求时,将验证规则放在表单中,则数据不会被验证/过滤,因为验证绑定在表单中。



有可能拥有独特的集中式验证器系统吗?在我看来,数据必须在保存在数据库之前进行验证,而不是在表单中!

想法?

解决方案

您可以在文档表单和操作


<在Zend Framework 2中,这是使用输入过滤器完成的,它可以是独立的,也可以在任何类中定义实现InputFilterAwareInterface接口的元素。 $ b

因此,在此示例中,模型实体实现 InputFilterAwareInterface ,并且有方法 setInputFilter getInputFilter 即可。因此,稍后您可以调用isValid()。






我个人将所有过滤器放入 src / ModuleName / Filter / (UserFilter.php)。其中实现了InputFilterAwareInterface并定义了所有脏东西的getInputFilter()方法。

在控制器或任何其他类中,只需调用:

 使用ModuleName\Filter\UserFilter; 

...

$ filter = new UserFilter();
$ data = $ this-> params() - > fromPost(); $($ $
$ b)if(!$ filter-> getInputFilter() - > setData($ data) - > isValid()){
$ data = $ filter-> getInputFilter - >的GetValues();
$ errors = $ filter-> getInputFilter() - > getMessages();
//抛出异常
}


Using Zend Framework 2. In my application, to edit the data in the database is possible compile an html form or send an http post request(my server is implemented as a web service). In this second case the form is not rendered. Problem: If I put the validations rules in the form when the server recive a post request sent not from the form but from a generic http post request (like an mobile app) the data is not validated/filtered becouse the validations are bind in the form.

Is possible to have an unique centralized validator system ? In my opinion the data must be validate before saving in the db, not in the form!

Ideas?

解决方案

You can find a similar example in the documentation Forms and Actions

In Zend Framework 2 this is done using an input filter, which can either be standalone or defined within any class that implements the InputFilterAwareInterface interface.

So, in this example model entity implements the InputFilterAwareInterface and there are methods setInputFilter and getInputFilter. So later you can call isValid().


I personally put all my filters into src/ModuleName/Filter/ (UserFilter.php). Where implements InputFilterAwareInterface and define getInputFilter() method with all dirty things.

Than in controller, or any other class, just call:

use ModuleName\Filter\UserFilter;

...

$filter = new UserFilter();
$data   = $this->params()->fromPost();

if(!$filter->getInputFilter()->setData($data)->isValid()){
    $data   = $filter->getInputFilter()->getValues();
    $errors = $filter->getInputFilter()->getMessages();
    // Throw an exception
}

这篇关于zend框架在模型中验证数据,而不是在表单中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆