Question

I have the following controller class:

SchoolController extends Controller:

// Mainly for AJAX requests
+ searchSchoolDataAction()
+ searchGradeDataAction()
+ searchPeriodDataAction()

// Entry point for a school website
+ schoolAction(shortName)

// Pre-enrolment process users from a certain school can perform
+ startPreEnrolmentAction(shortName)
+ preEnrolmentStudentAction(school)
+ preEnrolmentTutorAction(school)

And so on.

Now. It is a well known principle that we should keep controllers thin, and model thick. Additionally, controllers should also follow the Single Responsibility Principle. And my controllers have been gaining a lot of weight. So, here's the question: regarding best practices on MVC and OOP, when should I create a new controller, and when should I add a new method to a controller? Moreover, what's a good example of a controller method, or is this something left up to the programmer? (If the latter, it sounds a bit counterintuitive given it's a principle to be followed, but I'm not sure.) Thank you beforehand.

Was it helpful?

Solution

Controller should only deals with user request and Add a new Method only when you need to display web page. For example, you need to create CRUD for single Table suppose countries.

Your Controller Would be Countries. And Controller Actions represent Web pages Like, fetchAllAction, AddAction, UpdateAction, DeleteAction.

If your Project is for long time run, Then You Should build your Models on Enterprise Architecture. Enterprise Architecture Consist on four layers. i) Data Model. ii) Domain Logic Models. iii) Mappers. iv) Services. Note: Service Layer is the only gateway and Public Face to your Controller.

OTHER TIPS

From my experience, SRP is important when designing both controller methods and new controller.

Consider your basic controller method should only contain logic like filling view models from DB/service query and rendering viewmodel to your view.

SRP on creating controllers should be on a broader sense. From my experience it is a combination of maintenance, extensibility and user experience consideration.

Consider the case of the "Accounting" section in a CRM system. You may want to use one controller to represent all aspects of accounting department, but you can also break it into "Invoice", "Tax", "Payroll", etc. Using multiple controllers can improve user experience as they will know from the URI what you page is actually doing. And multiple controllers allow you to slim down your massive controllers into multiple specific controllers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top