Routes are configured within the application from the /config/routes.php file. For private routes that require authentication, App\Middleware\JwtAuthenticationMiddleware is used.
declare(strict_types=1);
use Mezzio\Application;
use Mezzio\MiddlewareFactory;
use App\Middleware\JwtAuthenticationMiddleware;
use Psr\Container\ContainerInterface;
return static function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
// public
$app->route('/api/auth/token', App\Handler\Api\AuthHandler::class, ['POST']);
$app->route('/api/auth/refresh', [App\Handler\Api\AuthHandler::class], ['POST']);
// private
$app->route('/api/auth/changePassword', [JwtAuthenticationMiddleware::class, App\Handler\Api\AuthHandler::class], ['PUT']);
$app->route('/api/auth/logout', [JwtAuthenticationMiddleware::class, App\Handler\Api\AuthHandler::class], ['GET']);
}
Another private route example;
return static function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
// private
$companies = [
JwtAuthenticationMiddleware::class,
Mezzio\Authorization\AuthorizationMiddleware::class,
App\Handler\Api\CompanyHandler::class
];
$app->route('/api/companies/create', $companies, ['POST']);
$app->route('/api/companies/update/:companyId', $companies, ['PUT']);
$app->route('/api/companies/delete/:companyId', $companies, ['DELETE']);
$app->route('/api/companies/findAll', $companies, ['GET']);
$app->route('/api/companies/findAllByPaging',$companies, ['GET']);
$app->route('/api/companies/findOneById/:companyId', $companies, ['GET']);
}
$apiHandler = [
App\Middleware\SetLocaleMiddleware::class,
App\Middleware\VersionValidateMiddleware::class,
App\Handler\ApiIndexHandler::class
];
$app->route('/api/:version/.*', $apiHandler, ['GET'], 'doc_index')
->setOptions(
[
'constraints' => [
'version' => '\d.{1,4}',
],
]
);
For more detailed information about the routes, see the link Laminas Router.
To test whether the /api/:version/.* route shown above works or not, let's create a middleware named RouteTestMiddleware in the App\Middleware\ folder.
declare(strict_types=1);
namespace App\Middleware;
use Mezzio\Router\RouterInterface;
use Mezzio\Router\Result as RouteResult;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\I18n\Translator\TranslatorInterface;
class RouteTestMiddleware implements MiddlewareInterface
{
protected $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$routeResult = $request->getAttribute(RouteResult::class);
$params = $routeResult->getMatchedParams();
print_r($params);
return $handler->handle($request);
}
}
We must define this middleware, which we created for testing purposes, in the pipeline.php file as follows.
config/pipeline.php
use App\Middleware\RouteTestMiddleware;
// Register your middleware in the middleware pipeline.
$app->pipe(RouteTestMiddleware::class);
Test the middleware by visiting the route address.
http://demo.local/api/1.0/index.html
As a result of the test, you should get an output like the following.
/*
[version] => 1.0
*/
Returns the current url path value.
echo $route->getPath(); // /docs/php-api/routes
Assigns a name to the route.
$route->setName('auth');
Returns to route name.
echo $route->getName(); // 'auth'
Returns to route middleware.
$route->getMiddleware();
Returns route specific methods.
$route->getAllowedMethods(); // ['POST', 'GET']
Lets you understand whether the specified method is allowed by the route.
$route->allowsMethod('POST'); // true
Lets you know if any method is allowed by the route.
$route->allowsAnyMethod(); // true
Allows you to assign options to the route.
$route->setOptions(
[
'constraints' => [
'version' => '\d.{1,4}',
],
]
);
Returns to route options.
$result = $request->getAttribute(Mezzio\Router\result::class);
If the result represents successful redirection, it returns true.
var_dump($result->isSuccess());
// true
Returns the route object that resulted in the route match.
echo get_class($result->getMatchedRoute()); // Mezzio\Router\Route
Allows you to get the matching route name. If this result is unsuccessful, set to false; otherwise, it returns the matching route name.
echo $result->getMatchedRouteName(); // /api/auth/token^POST
Matching route returns parameters. It is guaranteed to return an array even if the parameter is empty.
print_r(array_keys($result->getMatchedParams())); // Array ([0] => middleware)
If this route match fails, it returns true.
var_dump($result->isFailure());
// false
The result returns false if there is a redirect failure due to the HTTP method.
var_dump($result->isMethodFailure());
// false
Returns the methods allowed for this route.
print_r($result->getAllowedMethods()); // Array ([0] => POST)
For more information you can visit https://docs.mezzio.dev/mezzio/v3/features/router/intro.