我正在尝试运行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不使用自动加载器时,它会尝试使用一些自己的自动加载器。它看起来很难看,我该怎么做才能解决它?
答案 0 :(得分:12)
好的,我自己回答了我的问题。我必须在autoloader文件中的某处注册注释:
\Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
'JMS\Serializer\Annotation', __DIR__.'/vendor/jms/serializer/src'
);
答案 1 :(得分:0)
独立JMS序列化程序库的完整配置示例可能是:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:var="http://schemas.microsoft.com/BizTalk/2003/var"
exclude-result-prefixes="msxsl var s0 " version="1.0"
xmlns:ns0="http://schemas.microsoft.com/namespace1"
xmlns:s0="http://schemas.microsoft.com/BizTalk/2003/aggschema"
xmlns:s7="http://Schemas.RepeatingItemMessageInformation">
<xsl:output omit-xml-declaration="yes" method="xml" version="1.0" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="s0:Root">
<xsl:apply-templates select="InputMessagePart_0/node()"/>
</xsl:template>
<!-- Don't copy the other repeatingItem elements-->
<xsl:template match="ns0:repeatingItem[position()!=/s0:Root/InputMessagePart_1/s7:MessageInformation/RepeatingItemPosition]"/>
<xsl:template match="ns0:doc">
<ns0:doc>
<xsl:copy-of select="@*[local-name()!='archived']"/>
<xsl:attribute name="archived">0</xsl:attribute>
</ns0:doc>
</xsl:template>
<xsl:template match="ns0:ChildNode3/ns0:levelA/ns0:OtherDoc[not(@id = ancestor::ns0:ChildNode3/descendant::ns0:repeatingItem[number(/s0:Root/InputMessagePart_1/s7:MessageInformation/RepeatingItemPosition)]//ns0:doc/@id)]"/>
</xsl:stylesheet>
在这里,我使用Doctrine提供的Annotation注册表注册 JMS \ Serializer \ Annotation 命名空间。一旦完成,一切都按预期工作。