Skip to content

Support for content type #13

@nbish11

Description

@nbish11

What are your thoughts about adding support for content negotiation in the actions?

In the action, using content negotiation methods:

final class GetPhoto
{
    public function html(int $id)
    {
        return new HtmlResponse($this->domain->findById($id));
    }
    public function json(int $id)
    {
        return new JsonResponse($this->domain->findById($id));
    }
}

or using an accepts method:

final class GetPhoto
{
    public function accepts()
    {
        return ['text/html', 'application/json'];
    }
    public function __invoke(int $id)
    {
        // The response is built based off the request format
        return $this->responder->__invoke($this->request, $this->domain->findById($id));
    }
}

The script for both scenarios above:

$matched = $autoRoute->route($request->method, $request->pathInfo, $request->contentType);
$matched->format = /* 'application/json' or 'text/html' */;

// if found for separate content negotiation methods
$matched->method = /* json() or html() */;

// or if found for one single method
$matched->method = /* __invoke() */;

// if not found
$matched->error = /* AutoRoute\Exception\NotAcceptable */;

Personally, I like the first method, as it's simpler to understand and allows more flexibility. However, from my understanding of the ADR pattern, its the responsibility of the Responder to build and return the response as either HTML, JSON, XML, etc. Maybe, the library can support both methods?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions