Controllers are a place where most of your business logic will be. Controllers are where you put the responses you see in the web browser. Responses can be dictionaries, lists, views or any class that can render a response.
You may use a craft command to create a new basic controller or simply make a new controller manually. Controllers are classes with methods that are mapped to a route.
Your route may look something like this:
In this case this route will call the WelcomeController
classes show
method.
To create a basic controller via a craft command simply run:
This will create a new controller class to get you setup quickly. This controller class will look like a basic class like this:
You may start building your controller out and adding the responses you need.
Note that the controllers inherit Masonite base
Controller
class. This is required for Masonite to pick up your controller class in routes.
Your controller's constructor and controller methods are resolved by Masonite's Service Container. Because of this, you can simply typehint most of Masonite's classes in either the constructor or the methods:
Read more about the benefits of the Service Container.
Controllers can have different response types based on what you need to return.
If you want to return a JSON response you can return a dictionary or a list:
This will return an application/json
response.
You can return strings:
If you want to return a view you can resolve the view class and use the render method:
If you are using Masonite ORM, you can return a model directly:
If you want to return a redirect you can resolve the response class and use the redirect method:
You can return any class that contains a get_response()
method. This method needs to return any one of the above response types.
If you had a parameter in your route, you may fetch it by specifying the parameter in the controller's method:
Since the id
parameter is in the route we can fetch the value of this parameter by specifying it in the controller method signature:
Another way to fetch route parameters is through the request class:
Masonite will be able to pick up controllers (inheriting Controller
class) using string binding in the registered controllers locations.
The default registered controllers location is app/controllers
and is defined in project Kernel.py
configuration file:
You can override the registered controllers location in Kernel.py
file by editing the default binding controllers.location
.
You can multiple additional controller locations with add_controller_locations
:
The best place to do this is in your Kernel.py
file in the register_routes()
method.
You should do it before registering routes, else registering routes will fail as Masonite will fail to resolve controller classes.