Question

I'm currently implementing a RESTful API using an MVC framework. I have set up some controllers which allow me to access data on some general collections, for example:

GET /products
GET /products/1
GET /users
GET /users/1

My controller is structured so that it has a method for get(), post(), put(), and delete() which match up the the HTTP verb made by the incoming request. Then in the get() function for example I check if the id is present and workout whether to get a single object or an array, like this:

public function action_get()
{
    $id = (int) $this->request->param('id');
    if (empty($id))
    {
        // return an array of everything
    }
    else
    {
         // return a specific object
    }
}

This all works fine. However the next step is to have a relationship to my products or users, so for example:

GET /users/1/transactions
GET /users/1/transactions/1

Now obviously I could add this into the action_get() method above but that would make it bloated. So should I create a separate controller for transactions and pass the user id as a parameter with some clever routing?

Était-ce utile?

La solution

Your users can have many transactions right? So it is better to have a separate controller for transactions. Just like you did for your users do it for transactions. Separation of Concerns

GET /transactions
GET /transactions/1

This way you'll not only benefit the simplicity of GET in your controller but also you can structure your controller to accept POST, DELETE, and PUT.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top