2013-08-26 123 views
0

我正在从CSV文件为我们的数据库(它正在mySql上运行)编写一个导入脚本。由于以doctrine实体进行导入非常缓慢且内存密集,因此我选择编写原生查询来执行导入任务。如何验证实体属性

但是,在实际导入之前,我需要验证csv文件中的值,并且我想知道是否有任何方法可以使用实体属性定义(已在orm xml文件中定义)来执行验证。例如,如果该字段已被定义为最大长度为255个字符的字符串,那么我可以如何获取该定义并对csv文件中的值进行验证。

我希望它是有道理的,请让我知道,如果我的问题是不明确的任何部分。

回答

1

在导入数据之前,您可以使用Symfony2验证程序服务来检查数据。但是,您必须添加最大长度约束作为断言。

例实体:

<?php 

// src/Acme/YourBundle/Entity/Author.php 
// ... 

use Symfony\Component\Validator\Constraints as Assert; 

class YourEntity 
{ 
    /** 
    * @Assert\Length(max=255) 
    */ 
    public $someString; 
} 

你的控制器,处理进口:

<?php 
// ... 
use Acme\YourBundle\Entity\YourEntity; 

public function indexAction() 
{ 
    //omitted: get your csv data first 

    // create a new instance of your entity 
    $entity = new YourEntity(); 
    // populate your entity with data from your csv file 
    $entity->setSomeString($stringFromCsvFile); 

    // get the validator and validate your entity 
    $validator = $this->get('validator'); 
    $errors = $validator->validate($entity); 

    if (count($errors) > 0) { 
     // there are errors! do something with them 
    } else { 
     // there are no errors, persist the entity 
     $em = $this->getDoctrine()->getManager(); 
     $em->persist($entity); 
     $em->flush(); 
    } 
} 

更多信息请参见http://symfony.com/doc/current/book/validation.html