Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

php - JMSSerializer stand alone - Annotation does not exist, or cannot be auto-loaded

I am attempting to use JMSSerializer as a stand alone library to map JSON responses from an API to my model classes and am running into some issues.

Executing the following code results in an exception:

<?php
require dirname(__DIR__) . '/vendor/autoload.php';

use JMSSerializerAnnotation AS JMS;

class Trii {
    /**
     * User ID for this session
     * @JMSSerializedName("userID")
     * @JMSAnnotation(getter="getUserId")
     * @JMSType("string")
     * @var string
     */
    private $userId;

    public function getUserId() {
        return $this->userId;
    }

    public function setUserId($userId) {
        $this->userId = $userId;
    }
}

$serializer = JMSSerializerSerializerBuilder::create()->setDebug(true)->build();
$object = $serializer->deserialize('{"userID":"Trii"}', 'Trii', 'json');
var_dump($object);
?>

Here is the exception

DoctrineCommonAnnotationsAnnotationException: [Semantical Error] The annotation "@JMSSerializerAnnotationSerializedName" in property Trii::$userId does not exist, or could not be auto-loaded.

I have the following libraries installed for the project via composer

{
    "require": {
        "jms/serializer": "1.0.*@dev"
    }
}

Is there something obvious I am missing since I am not using the whole Doctrine 2 solution?

EDIT: my final solution was to create a bootstrap file with the following content:

<?php
// standard composer install vendor autoload magic
require dirname(__DIR__) . '/vendor/autoload.php';

// Bootstrap the JMS custom annotations for Object to Json mapping
DoctrineCommonAnnotationsAnnotationRegistry::registerAutoloadNamespace(
    'JMSSerializerAnnotation',
    dirname(__DIR__).'/vendor/jms/serializer/src'
);
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pretty sure this enables silent auto-loading which is much more convenient than registering the namespaces yourself.

AnnotationRegistry::registerLoader('class_exists');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...