문제

Is it good design to have a controller for each object of your API? I know this is a short question, but it's really a fundamental question that I do not know. Say I have a school or a CRM. That is a lot of controllers. I don't know another way to do it, but it feels like a DRY problem.

I am using ASPNET Core if that matters.

EDIT: By object I meant the actual classes in my project. But the answers have cleaned that up. I was thinking about it as a sole one-to-one correspondence.

도움이 되었습니까?

해결책

Define 'object'

You have one controller for each resource. Where a resource is a thing that your API provides (user, customer, student, sports-team, etc.)

Resources don't necessarily map one-to-one to domain objects. Sometimes a resource is made up of several domain objects and sometimes several resources reference the same domain objects.

A controller may return several representations of the same resource, depending on how it's called. Generally it's only two though.

A summary of the resource when returning a list:

GET /students

[
    { id: 1, name: "john smith" },
    { id: 2, name: "jane smythe" }
]

And a detailed representation when getting a specific item

GET /students/1

{
    id: 1,
    name: "john smith",
    age: 27,
    location: "Venezuela"
}

If a resource has a strong dependency on a parent resource (e.g. a room cannot exist without the building it's in), I would still have a room controller and handle the dependency via required properties and business logic. (i.e. room must specify building_id)

To put the room logic in the building controller is giving it too many responsibilities.

다른 팁

I'd say usually YES because if you have less, you will give more than one responsability to the same controller, which is not good.

I see one case where you could not need one controller : It's when an object A has a strong relationship with another parent object B and don't have any independant operation. Then that object A will be managed by the object B of the association. It is possible than in the lower layer (service, database) you will delegate A's operation to a specific class for him, but this will be not visible from the API's view.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top