I'm trying to use the JMSSerializerBuilder
to encode my objects in json to be able to make AJAX calls.
I've succesfully installed the bundle through composer.
Then, following the official documentation, I'm doing:
<?php
namespace Pondip\GeolocBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use JMS\Serializer\SerializerBuilder;
class DefaultController extends Controller
{
public function getLakesSurroundingAction($lat=0, $lng=0, $limit = 50, $distance = 50, $unit = 'km')
{
$lakesNearby= $this->getNearby($lat, $lng, $limit, $distance, $unit);
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$return = $serializer->serialize($return, 'json');
}
}
But it returns
FatalErrorException:
Error: Class 'Pondip\GeolocBundle\Controller\JMS\Serializer\SerializerBuilder' not found in C:\Program Files (x86)\wamp\www\Pondip Dev\src\Pondip\GeolocBundle\Controller\DefaultController.php line 51
line 51 is:
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
Why is that happening? When removing the use JMS\Serializer\SerializerBuilder;
line (since it is not specified in the doc) I just get an internal server error.
That's because you don't use namespaces correctly. An use statements generates an alias for a specific namespace. The use JMS\Serializer\SerializerBuilder;
statement means that SerializerBuilder
is an alias for the JMS\Serializer\SerializerBuilder
class.
When doing $serializer = JSM\Serializer\SerializerBuilder::create()
in your code, it is an unqualified-namespace, which means it gets into the current namespace. That means PHP is searching for a Pondip\GeolocBundle\Controller\JMS\Serializer\SerializerBuilder
(as you're in the Pondip\GeolocBundle\Controller\
namespace).
To fix this, just use $serializer = SerializerBuilder::create()
. Because we've set up an alias for the SerializerBuilder
, it gets to the correct class and everything works.
For more information, please take a look at some "PHP namespacing" tutorials, like this one.
With use JMS\Serializer\SerializerBuilder;
in place you should address the class just as SerializerBuilder
. Without it, use the fully qualified name \JMS\Serializer\SerializerBuilder
(notice the leading backslash!)
Further reference: http://www.php.net/manual/en/language.namespaces.basics.php
I personnaly had to use $this->container->get('serializer');
instead of $serializer = $container->get('jms_serializer');