Controllers
Definitions
Controllers are PHP classes responsible for handling HTTP requests and generating corresponding responses. They are located in the src/Controller
directory.
The methods within these controllers are responsible for handling HTTP requests. They should return an instance of the Qwwwest\Namaskar\Response
class, representing the HTTP response returned by the controller.
Attributes
Attributes are a new feature introduced in PHP8 that allows adding metadata and annotations to code elements such as classes, properties, methods, and function parameters.
An attribute is a comment that adds additional information to your code to provide specific instructions to development tools, frameworks, or libraries that analyze and use these attributes. Attributes can be used for various features, such as configuring routes, data validation, defining constraints, managing permissions, etc.
Attributes are defined using the #[AttributeName]
prefix, followed by parentheses, optionally with parameters, to specify additional details. The following example will make this clearer:
Controllers use attributes to define routes. You can use the #[Route]
attribute to specify the route path, accepted HTTP methods, and other options such as validation requirements and route names. Here's an example of using the #[Route]
attribute:
<?php
namespace App\Controller;
use Qwwwest\Namaskar\Response;
use Qwwwest\Namaskar\AbstractController;
class MyController extends AbstractController
{
#[Route('/my-route', methods: ['GET'], name: 'my_route')]
public function myRoute(): Response
{
// Processing logic
return new Response('Hello, Route!');
}
}
An object of Qwwwest\Namaskar\Response
is returned by the controller. This class is used to specify the content, headers, status codes, and other response details.
Redirections
To perform a redirection, you can use the redirect()
method of the response object ($this->response
) in your controllers. Here's an example of redirection:
<?php
namespace App\Controller;
use Qwwwest\Namaskar\Response;
class MyController extends AbstractController
{
public function redirectToHome(): Response
{
return $this->response->redirect('/');
}
}
In this example, the redirectToHome()
method redirects to the home page using the redirect()
method of the response object.
Handling 404 Errors
To handle 404 errors, you can use a special method in your controller:
<?php
namespace App\Controller;
use Qwwwest\Namaskar\Response;
class ErrorController extends AbstractController
{
public function notFound(): Response
{
$content = 'Page not found';
$statusCode = 404;
return new Response($content, $statusCode);
}
}
In this example, the notFound()
method generates a response with the content "Page not found" and the status code 404, indicating a 404 error.