When trying to make a function that serializes an object, turn it into a json and send it as a http response I get the following error:
ContextErrorException
Runtime Notice: Declaration of AppBundle\Controller\DefaultController::json() should be compatible with Symfony\Bundle\FrameworkBundle\Controller\Controller::json($data, $status = 200, $headers = Array, $context = Array)
I was able to show an array of users via var_dump(); before I tried to serialize the object and use it in a function. Here's my code:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
// replace this example code with whatever you need
return $this->render('default/index.html.twig', [
'base_dir' =>realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
]);
}
public function pruebasAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository('BackendBundle:User')->findAll();
return $this->json($users);
}
public function json($data){
$normalizers = array(new ObjectNormalizer());
$encoders = array(new JsonEncoder());
$serializer = new Serializer($normalizers, $encoders);
$json = $serializer->serialize($data, 'json');
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
What does the "public function json($data){ }" do to be messing up with the program?
and how do I make my json compatible with the one in the framework?
P.D.: Be patience. I'm new with the framework