| breadcrumb |
|
||
|---|---|---|---|
| summary-order | 2; 1 | ||
| keywords |
|
It's classes whose control interactions between models, services and templates. The controller is instanced, and the matched method is called, by router service when the application started.
It's the main controller for website projects who offer methods for services, routing, templating, flash messages, and redirection.
use Berlioz\Http\Core\Controller\AbstractController;
use Berlioz\Http\Message\Response;
use Berlioz\Router\Attribute\Route;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
class MyController extends AbstractController
{
#[Route('/my-route/{attr1}')]
public function myMethod(ServerRequestInterface $request): ResponseInterface
{
$attribute = $request->getAttribute('attr1');
return $this->response('Hello ' . $attribute);
}
}Parameters of the controllers methods are automatically inject by the
class Instantiator
of service container.
Attributes of routes are available with ServerRequest parameter, with method getAttributes().
The AbstractController class provides several helper methods through traits.
From ResponseHelperTrait:
-
response(mixed $body = null, int $statusCode = 200, array $headers = []): ResponseInterfaceCreate a response. If the body is empty and status is 200, it will be automatically changed to 204 (No Content).
-
jsonResponse(mixed $body = null, int $flags = 0, int $statusCode = 200, array $headers = []): ResponseInterfaceCreate a JSON response. The body is encoded with
json_encode(). AContent-Type: application/jsonheader is automatically added. -
redirect(UriInterface|string $uri, int $httpResponseCode = 302, ?ResponseInterface $response = null): ResponseInterfaceRedirect to a given URI. If a response object is provided, it will be completed with the Location header.
From RouterHelperTrait:
-
getRouter(): RouterInterfaceGet the router service.
-
getRoute(): ?RouteInterfaceGet the current matched route.
-
path(string|RouteInterface $name, array|RouteAttributes $parameters = []): UriInterfaceGenerate a path for a named route.
-
finalize_path(string $path): stringFinalize a path (apply router prefix, etc.).
From ReloadHelperTrait:
-
reload(array $queryParams = [], bool $mergeQueryParams = false, ?ResponseInterface $response = null): ResponseInterfaceReload the current page. Deprecated: use
redirect()instead.
-
addFlash(string $type, string $message): staticAdd a flash message to the flash bag.
-
get(string $id): mixedGet a service from the service container.
From TwigAwareTrait (when berlioz/twig-package is installed):
-
render(string $name, array $variables = []): stringRender a Twig template.