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

前端 未结 6 1497
遥遥无期
遥遥无期 2020-12-13 18:00

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 fo

6条回答
  •  失恋的感觉
    2020-12-13 18:29

    I ran into the same problem and found your question through Google. Unfortunately you hadn't yet received any answers, so I had to dig in myself. :P

    The thing is, Doctrine Annotations, which JMSSerializer Annotations uses, does NOT use normal PHP autoloading.

    How are these annotations loaded? From looking at the code you could guess that the ORM Mapping, Assert Validation and the fully qualified annotation can just be loaded using the defined PHP autoloaders. This is not the case however: For error handling reasons every check for class existence inside the AnnotationReader sets the second parameter $autoload of class_exists($name, $autoload) to false. To work flawlessly the AnnotationReader requires silent autoloaders which many autoloaders are not. Silent autoloading is NOT part of the PSR-0 specification for autoloading.

    This means you have to register the Annotation file(s) yourself:

    AnnotationRegistry::registerFile(
        . 
       "/vendor/jms/serializer/src/JMS/Serializer/Annotation/SerializedName.php");
    

    ... or the whole namespace (preferred method):

    AnnotationRegistry::registerAutoloadNamespace(
        'JMS\Serializer\Annotation', 
         . "/vendor/jms/serializer/src");
    

    Be careful with the path in registerAutoloadNamespace. I first tried to register the whole path to annotations in the same manner with registerFile:

     . "/vendor/jms/serializer/src/JMS/Serializer/Annotation 
    

    but that failed miserably. :D

    I hope this gets you a step further. :)

提交回复
热议问题