Controllers
Last updated
Was this helpful?
Last updated
Was this helpful?
Instead of defining all of your request handling logic as Closures in routes/web.php file, you may want to organise them using Controller classes.
Controllers are stored in the app/Controllers
directory by default but in yuga, everything is configurable which means you can put them in app/AnyFolder
and map them to the appropriate namespace
Defining Controllers
Below is an example of a basic controller class. Note that the controller extends the base controller class that comes with Yuga. The base class provides a few convenience methods such as the middleware
method, which can be used to attach middleware to controller methods:
The route that corresponds to this controller is as below:
Constructor Injection
You can also type-hint any Yuga classes and interfaces If the container can resolve them, you can type-hint them.
Method Injection
In addition to constructor injection, you can also type-hint dependencies on your controller's methods. A common use-case for method injection is injecting the Yuga\Http\Request
instance into your controller methods:
If your controller method is also expecting input from a route parameter, list your route arguments any where with other dependencies, remember, Route parameters are injected into route callbacks / controllers based on their names in the Route defined, the order of getting them in callback / controller does not matter. For example, if your route is defined like so:
You may still type-hint the Yuga\Http\Request
and access your id
parameter by defining your controller method as follows:
OR, like so:
Creating Controllers using yuga console command
Controllers can be created using the php yuga make:controller
command
i.e php yuga make:controller UsersController
would produce the following scaffold:
The Yuga is used to resolve all Yuga controllers. As a result, you are able to type-hint any dependencies your controller may need in its constructor. The declared dependencies will automatically be resolved and injected into the controller instance: