tebru / gson-php

Gson implemented in PHP
Other
151 stars 18 forks source link

What's the right way of using annotations? #7

Closed nicolas-cajelli closed 7 years ago

nicolas-cajelli commented 7 years ago

Hey, I want to start saying that this looks like a really nice package, it was needed for a long time.

I have a doubt about annotations, since docs are no so clear on how to use it.

I have created a class, which has a single property, and i want to use SerializedName to map the json attribute to the class property:

class User
{
   /**
    * @SerializedName("id")
    */
   protected $userId;
}

I've done several variations of the above code (with \ as first char, with the whole namespace, with the use at the beginning of the class) and all ends on pretty much the same output: [Semantical Error] The annotation \"@Tebru\\Gson\\Annotation\\SerializedName\" in property User::$userId does not exist, or could not be auto-loaded.

The only two things that worked so far are:

I've seen that AnnotationRegistry is referenced on the tests, is that the actual fix for my problem?

Thanks

natebrunette commented 7 years ago

Hi @nicolas-cajelli,

Yes, you need to register that annotation loader

$loader = require __DIR__ . '/../vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);

This should do what you need. I'll make a note to update that docs, thanks.

Let me know if you have any additional questions.

(I need to figure out why github isn't notifying me of new issues, sorry for the delayed response.)

natebrunette commented 7 years ago

Docs are updated

https://github.com/tebru/gson-php/blob/master/README.md#installation https://github.com/tebru/gson-php/blob/master/docs/Annotations.md#annotation-reference

Please reopen if you run into any additional issues.