Zend框架2与原则的验证2 [英] Validation in Zend Framework 2 with Doctrine 2

查看:99
本文介绍了Zend框架2与原则的验证2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在让自己越来越熟悉Zend Framework 2,同时我在Zend Framework 2中使用了验证部分进行了更新。我看到很少的例子,如何使用Zend验证数据库中的数据Db适配器,例如来自Zend Framework 2官方网站的代码:

  //检查数据库中不存在该用户名
$ validator = new Zend\Validator\Db\NoRecordExists(
array(
'table'=>'users',
'field'=>'username'

);
if($ validator-> isValid($ username)){
//用户名似乎有效
} else {
//用户名无效;打印原因
$ messages = $ validator-> getMessages();
foreach($ messages as $ message){
echo$ message\\\
;
}
}

现在我的问题是如何做验证部分?



例如,我需要在插入数据库之前验证一个名称,以检查数据库中不存在相同的名称,我已经更新了Zend Framework 2示例相册模块要使用Doctrine 2与数据库进行通信,现在我想将验证部分添加到我的代码中。



让我们说在将相册名称添加到数据库之前,我想验证数据库中不存在相同的相册名称。



有关这方面的任何信息都将非常有用!

解决方案

我有同样的问题,解决了这样:


  1. 创建一个自定义的验证器类,命名为 NoEntityExists 或任何你想要的。)

  2. 扩展 Zend\Validator\AbstractValidator

  3. 提供一个getter和setter为 Doctrine\ORM\EntityManager

  4. 为选项(entityname,...)提供一些额外的getter和setter )

  5. 创建一个 isValid($ value)方法来检查一条记录是否存在并返回一个布尔值

  6. 要使用它,创建一个新的实例,分配 EntityManager ,就像任何其他验证器一样使用它。

T o了解如何实现验证器类,检查已存在的验证器(最好是像回调 GreaterThan )。



希望我可以帮助你。



//编辑:对不起,我是迟到; - )



所以这里是一个非常高级的例子,说明如何实现这样一个验证器。



请注意,我添加了一个 translate()方法,以便使用PoEdit捕获语言字符串(一种翻译助手工具,从源代码中获取这样的字符串,并将它们放入列表中您)。如果您没有使用 gettext(),那么您可能会略过这一点。



此外,我的第一个类与ZF2,我不会把它放入应用程序模块。也许,创建一个更好的新模块,例如 MyDoctrineValidator 等。



这个验证器给你很多灵活性,因为您必须先设置查询才能使用它。当然,您可以在选项中预定义查询并设置实体,搜索列等。有乐趣!

 <?php 
命名空间Application\Validator\Doctrine;

使用Zend\Validator\AbstractValidator;
使用Doctrine\ORM\EntityManager;

class NoEntityExists extends AbstractValidator
{
const ENTITY_FOUND ='entityFound';

protected $ messageTemplates = array();

/ **
* @var EntityManager
* /
protected $ entityManager;

/ **
* @param string
* /
保护$ query;

/ **
*确定空值(null,空字符串)是否将< b> NOT< / b>包括在支票中。
*默认为true
* @var bool
* /
protected $ ignoreEmpty = true;

/ **
*用PoEdit捕获邮件的虚拟...
* @param string $ msg
* @return string
* /
public function translate($ msg)
{
return $ msg;
}

/ **
* @返回$ ignoreEmpty
* /
public function getIgnoreEmpty()
{
return $ this-> ignoreEmpty;
}

/ **
* @param boolean $ ignoreEmpty
* /
public function setIgnoreEmpty($ ignoreEmpty)
{
$ this-> ignoreEmpty = $ ignoreEmpty;
return $ this;
}

/ **
*
* @param unknown_type $ entityManager
* @param unknown_type $ query
* /
public function __construct($ entityManager = null,$ query = null,$ options = null)
{
if(null!== $ entityManager)
$ this-> setEntityManager EntityManager的);
if(null!== $ query)
$ this-> setQuery($ query);

//初始消息
$ this-> messageTemplates [self :: ENTITY_FOUND] = $ this-> translate('已经有一个具有此值的实体。

return parent :: __ construct($ options);
}

/ **
*
* @param EntityManager $ entityManager
* @return \Application\Validator\Doctrine\NoEntityExists
* /
public function setEntityManager(EntityManager $ entityManager)
{
$ this-> entityManager = $ entityManager;
return $ this;
}

/ **
* @返回$ query
* /
public function getQuery()
{
return $ this-> query;
}

/ **
* @param field_type $ query
* /
public function setQuery($ query)
{
$ this-> query = $ query;
return $ this;
}

/ **
* @return \Doctrine\ORM\EntityManager
* /
public function getEntityManager()
{
return $ this-> entityManager;
}

/ **
*(非PHPdoc)
* @see \Zend\Validator\ValidatorInterface :: isValid()
* @throws Exception\RuntimeException()在EntityManager或查询丢失的情况下
* /
public function isValid($ value)
{
//提取entityManager
$ em = $ this-> getEntityManager();

if(null === $ em)
throw new Exception\RuntimeException(__ METHOD__。没有entityManager设置。

//获取查询
$ query = $ this-> getQuery();

if(null === $ query)
throw new Exception\RuntimeException(__ METHOD__。没有查询集。

//忽略空值?
if((null === $ value ||''=== $ value)&& $ this-> getIgnoreEmpty())
return true;

$ queryObj = $ em-> createQuery($ query) - > setMaxResults(1);

$ entitiesFound = !! count($ queryObj-> execute(array(':value'=> $ value)));

//设置错误消息
if($ entitiesFound)
$ this-> error(self :: ENTITY_FOUND);

//如果没有找到记录,则有效 - >结果计数为0
返回! $ entitiesFound;
}
}


I am right now getting myself more and more familiar with Zend Framework 2 and in the meantime I was getting myself updated with the validation part in Zend Framework 2. I have seen few examples how to validate the data from the database using Zend Db adapter, for example the code from the Zend Framework 2 official website:

//Check that the username is not present in the database
$validator = new Zend\Validator\Db\NoRecordExists(
    array(
        'table' => 'users',
        'field' => 'username'
    )
);
if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

Now my question is how can do the validation part?

For example, I need to validate a name before inserting into database to check that the same name does not exist in the database, I have updated Zend Framework 2 example Album module to use Doctrine 2 to communicate with the database and right now I want to add the validation part to my code.

Let us say that before adding the album name to the database I want to validate that the same album name does not exist in the database.

Any information regarding this would be really helpful!

解决方案

I had the same problem and solved it this way:

  1. Create a custom validator class, name it something like NoEntityExists (or whatever you want).
  2. Extend Zend\Validator\AbstractValidator
  3. Provide a getter and setter for Doctrine\ORM\EntityManager
  4. Provide some extra getters and setters for options (entityname, ...)
  5. Create an isValid($value) method that checks if a record exists and returns a boolean
  6. To use it, create a new instance of it, assign the EntityManager and use it just like any other validator.

To get an idea of how to implement the validator class, check the validators that already exist (preferably a simple one like Callback or GreaterThan).

Hope I could help you.

// Edit: Sorry, I'm late ;-)

So here is a quite advanced example of how you can implement such a validator.

Note that I added a translate() method in order to catch language strings with PoEdit (a translation helper tool that fetches such strings from the source codes and puts them into a list for you). If you're not using gettext(), you can problably skip that.

Also, this was one of my first classes with ZF2, I wouldn't put this into the Application module again. Maybe, create a new module that fits better, for instance MyDoctrineValidator or so.

This validator gives you a lot of flexibility as you have to set the query before using it. Of course, you can pre-define a query and set the entity, search column etc. in the options. Have fun!

<?php
namespace Application\Validator\Doctrine;

use Zend\Validator\AbstractValidator;
use Doctrine\ORM\EntityManager;

class NoEntityExists extends AbstractValidator
{
    const ENTITY_FOUND = 'entityFound';

    protected $messageTemplates = array();

    /**
     * @var EntityManager
     */
    protected $entityManager;

    /**
     * @param string
     */
    protected $query;

    /**
     * Determines if empty values (null, empty string) will <b>NOT</b> be included in the check.
     * Defaults to true
     * @var bool
     */
    protected $ignoreEmpty = true;

    /**
     * Dummy to catch messages with PoEdit...
     * @param string $msg
     * @return string
     */
    public function translate($msg)
    {
        return $msg;
    }

    /**
     * @return the $ignoreEmpty
     */
    public function getIgnoreEmpty()
    {
        return $this->ignoreEmpty;
    }

    /**
     * @param boolean $ignoreEmpty
     */
    public function setIgnoreEmpty($ignoreEmpty)
    {
        $this->ignoreEmpty = $ignoreEmpty;
        return $this;
    }

    /**
     *
     * @param unknown_type $entityManager
     * @param unknown_type $query
     */
    public function __construct($entityManager = null, $query = null, $options = null)
    {
        if(null !== $entityManager)
            $this->setEntityManager($entityManager);
        if(null !== $query)
            $this->setQuery($query);

        // Init messages
        $this->messageTemplates[self::ENTITY_FOUND] = $this->translate('There is already an entity with this value.');

        return parent::__construct($options);
    }

    /**
     *
     * @param EntityManager $entityManager
     * @return \Application\Validator\Doctrine\NoEntityExists
     */
    public function setEntityManager(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
        return $this;
    }

    /**
     * @return the $query
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * @param field_type $query
     */
    public function setQuery($query)
    {
        $this->query = $query;
        return $this;
    }

    /**
     * @return \Doctrine\ORM\EntityManager
     */
    public function getEntityManager()
    {
        return $this->entityManager;
    }

    /**
     * (non-PHPdoc)
     * @see \Zend\Validator\ValidatorInterface::isValid()
     * @throws Exception\RuntimeException() in case EntityManager or query is missing
     */
    public function isValid($value)
    {
        // Fetch entityManager
        $em = $this->getEntityManager();

        if(null === $em)
            throw new Exception\RuntimeException(__METHOD__ . ' There is no entityManager set.');

        // Fetch query
        $query = $this->getQuery();

        if(null === $query)
            throw new Exception\RuntimeException(__METHOD__ . ' There is no query set.');

        // Ignore empty values?
        if((null === $value || '' === $value) && $this->getIgnoreEmpty())
            return true;

        $queryObj = $em->createQuery($query)->setMaxResults(1);

        $entitiesFound = !! count($queryObj->execute(array(':value' => $value)));

        // Set Error message
        if($entitiesFound)
            $this->error(self::ENTITY_FOUND);

        // Valid if no records are found -> result count is 0
        return ! $entitiesFound;
    }
}

这篇关于Zend框架2与原则的验证2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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