A Controller
is the glue between your business logic and the requests made.
Although it can contain quite a few functionalities, they should all be specific to the target request in question.
A a small description of a controller, you will find similar cases as:
Controllers are the glue that binds models, views and other components together into a runnable application. Controllers are responsible for dealing directly with end user requests. Therefore, controllers
Understanding that, to keep your controllers focused you need to ask yourself the question: Is this functionality referred by the controller?
You can find inspiration in the laravel
way of organizing their MVC
. You will notice that they separated all authentication
requests into a AuthController
.
This AuthController
is responsible for:
-> capturing the POST
request that will contain the password and the email (or whatever other method you created).
-> Authenticate the user if successful;
-> redirect to the correct views depending on the results for auth
(back to login page or to show the dashboard);
The latest is where you have to start organizing your flow. Check this out:
-> If the user was succesfully authenticated, then you wish to present the dashboard
view;
-> the dashboard view is not really part of the AuthController
is more directly related to a DashboardController
. So, you will actually want to redirect from the AuthController
to the DashboardController
via routes
;
So the answer to your question is, it depends! If the logic you are adding to your controller is focusing on a specific business logic sector of your application, do not be bothered by the amount of methods
you might have. It all really depends of the complexity of your application;
BUT if you controller starts having methods that do many different things for many different sectors of you application, lets say you have a controller that:
->creates products
->deletes products;
->Authenticates users;
->list users;
-> etc
Then you are doing it wrong and not separating the business logic accordingly.
The controller responsibility is to glue together the request with the correct business logic and then redirect all the data to a correct view to display it.
It shouldn’t be aware on:
-> How the data is fetched (doing the Model job);
-> How the data should be parsed for display (doing the Marshaller job);
-> Checking if the data exists (doing the Hydrator job);
among other concerns. It literally does:
1. Oh! got a request from route `list/users`;
2. To list users I better call all users in my database (Call the Model);
3. Right, I believe they should be here, lets tell the view to be generated;
4. Here you go view, you list them as you wish, I dont really care;
Hope it helps!
2
solved BETTER WAY #PHP MVC [closed]