2013-08-26 56 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