2013-05-28 64 views
2

我想運行JMSSerializer。我簡單的代碼主義註釋加載失敗

use JMS\Serializer\Annotation\Type; 

class Comment 
{ 
    private $msg; 

    public function __construct($msg) 
    { 
     $this->msg = $msg; 
    } 
} 

class Person 
{ 
    /** 
    * @Type("array<Comment>") 
    */ 
    private $commentList; 

    public function addComment(Comment $comment) 
    { 
     $this->commentList[] = $comment; 
    } 
} 

$type = new Type; 
$serializer = JMS\Serializer\SerializerBuilder::create()->build(); 

$data = new Person(); 
$data->addComment(new Comment('hey')); 

var_dump($serializer->serialize($data, 'json')); 

失敗

PHP Fatal error: Uncaught exception 'Doctrine\Common\Annotations\AnnotationException' with message '[Semantical Error] The annotation "@JMS\Serializer\Annotation\Type" in property Person::$commentList does not exist, or could not be auto-loaded.' in xxx.php:52 

OK,但如果我添加行

$type = new Type; 

手動觸發自動加載磁帶機,它的工作原理:

string(32) "{"comment_list":[{"msg":"hey"}]}" 

正如我請參閱AnnotationRegistry不使用自動加載器,它三es使用一些自己的自動加載器。它看起來很醜陋,我需要做些什麼來修復它?

+0

可能重複[JMSSerializer獨立 - 註釋不存在,或不能自動加載](http://stackoverflow.com/questions/14629137/jmsserializer-stand-alone-annotation-does-not-exist-或者,不能待自動加載) –

回答

0

爲獨立JMS串行庫的完整配置示例可能是:

<?php 
namespace iMSCP\Service; 
use JMS\Serializer\Serializer; 
use JMS\Serializer\SerializerBuilder; 
use Doctrine\Common\Annotations\AnnotationRegistry; 
use iMSCP_Registry as Registry; 

/** 
* Class SerializerServiceFactory 
* @package iMSCP\Service 
*/ 
class SerializerServiceFactory 
{ 
    /** 
    * @var Serializer 
    */ 
    static $serialiszer; 

    public static function create() 
    { 
     if (static::$serialiszer === null) { 
      $config = Registry::get('config'); 
      AnnotationRegistry::registerAutoloadNamespace(
       'JMS\Serializer\Annotation', $config['CACHE_DATA_DIR'] . '/packages/vendor/jms/serializer/src' 
      ); 
      static::$serialiszer = SerializerBuilder::create() 
       ->setCacheDir(CACHE_PATH . '/serializer') 
       ->setDebug($config['DEVMODE']) 
       ->build(); 
     } 

     return static::$serialiszer; 
    } 
} 

在這裏,我註冊JMS \ Serializer \ Annotation命名空間使用由Doctrine提供的Annotation註冊表。完成後,所有工作都按預期工作。