[英]Cache:clear fails with The annotation “@Doctrine\ORM\Mapping\HasLifeCycleCallbacks” … does not exist
[英]Doctrine annotation loader fails
我正在尝试运行 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
好的,但如果我添加行
$type = new Type;
手动触发自动加载器,它的工作原理:
string(32) "{"comment_list":[{"msg":"hey"}]}"
正如我看到的 AnnotationRegistry 不使用自动加载器,它尝试使用一些自己的自动加载器。 看起来很丑,我该怎么做才能修复它?
好的,我自己回答我的问题。 我必须在自动加载器文件中的某处注册注释:
\Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
'JMS\Serializer\Annotation', __DIR__.'/vendor/jms/serializer/src'
);
其他方式: http : //docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/annotations.html#registering-annotations
独立 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;
}
}
在这里,我使用 Doctrine 提供的 Annotation 注册表注册JMS\\Serializer\\Annotation命名空间。 完成后,一切都按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.