Eduardo Medina
Eduardo Medina

Reputation: 43

PHP Controller responsibility

I have this Controller(I'm using PHP and Symfony):

class FinancialController extends Controller\AbstractController
{
    /*
     * @Route("/")
     * @Method({"GET"})
     * */
    public function index() {
        return $this->render('financial/index.html.twig');
    }
}

My entity looks like this:

class Financial
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @return mixed
     */

    /**
     * @ORM\Column(type="string")
     */
    private $name;

    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id): void
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): void
    {
        $this->name = $name;
    }
}

Suppose I want to send an array of Financial objects restfully to a javascript endpoint where should I put the JSON encoding part? in the controller? in the repository?

Upvotes: 0

Views: 156

Answers (2)

Jared Farrish
Jared Farrish

Reputation: 49188

As @yivi describes, serialization is generally an edge-side consideration, and an entity repository is an internal concern. There are times you serialize within the context of the request, but generally you're serializing the response (deserializing an incoming request, of course, based on the inbound content-type).

A more sophisticated approach would be content negotiation, which reads the Accepts and negotiates the best format to respond with, which may be JSON, XML, YAML, etc.

From the Symfony docs:

use Symfony\Component\HttpFoundation\Response;
// ...

public function index(): Response
{
    // returns '{"username":"jane.doe"}' and sets the proper Content-Type header

    return $this->json(['username' => 'jane.doe']);

    // the shortcut defines three optional arguments
    // return $this->json($data, $status = 200, $headers = [], $context = []);
}

https://symfony.com/doc/current/controller.html#returning-json-response

There's also just returning a JsonResponse.

Upvotes: 1

yivi
yivi

Reputation: 47329

Between those two choices, the "controller" seems like the more logical choice.

It's the one in charge of responding to user input and prepare the response for the client.

The repository is only there to mediate with the model, to perform the appropriate query via the corresponding persistence layer. It should have no knowlege whatsoever of the client format requirements, it simply queries the application model according to the controller requirements.

Get your entity collection from the repository, encode it as JSON in your controller and return the adequate response.

Upvotes: 3

Related Questions