Rotalar uygulama içerisinde /config/routes.php dosyasından konfigüre edilirler. Authentication gerektiren private rotalar için App\Middleware\JwtAuthenticationMiddleware kullanılır.
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']);
}
Bir başka private rota örneği;
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}',
],
]
);
Rotalar hakkında daha detaylı bilgi için Laminas Router bağlantısına göz atın.
Yukarıda gösterilen /api/:version/.* rotasını çalışıp çalışmadığını test etmek için App\Middleware\ klasörü içerisinde RouteTestMiddleware isimli bir ara katman yaratalım.
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);
}
}
Test amaçlı oluşturduğumuz bu ara katmanı pipeline.php dosyası içerisinde aşağıdaki gibi tanımlamalıyız.
config/pipeline.php
use App\Middleware\RouteTestMiddleware;
// Register your middleware in the middleware pipeline.
$app->pipe(RouteTestMiddleware::class);
Rota adresini ziyaret ederek ara katmanı test edin.
http://demo.local/api/1.0/index.html
Test sonucunda aşağıdaki gibi bir çıktı elde etmiş olmalısınız.
/*
[version] => 1.0
*/
Geçerli url path değerine geri döner.
echo $route->getPath(); // /docs/php-api/routes
Rotaya bir isim atar.
$route->setName('auth');
Rota ismine geri döner.
echo $route->getName(); // 'auth'
Rota ara katmanlarına geri döner.
$route->getMiddleware();
Rotaya tanımlı metotlara geri döner.
$route->getAllowedMethods(); // ['POST', 'GET']
Belirtilen yönteme rota tarafından izin verilip verilmediğini anlamanızı sağlar.
$route->allowsMethod('POST'); // true
Rota tarafından herhangi bir yönteme izin verilip verilmediğini anlamanızı sağlar.
$route->allowsAnyMethod(); // true
Rotaya opsiyonlar atamanızı sağlar.
$route->setOptions(
[
'constraints' => [
'version' => '\d.{1,4}',
],
]
);
Rotaya opsiyonlarına geri döner.
$result = $request->getAttribute(Mezzio\Router\result::class);
Sonuç başarılı yönlendirmeyi temsil ediyorsa true değerine döner.
var_dump($result->isSuccess());
// true
Rota eşleşmesiyle sonuçlanan rota nesnesine geri döner.
echo get_class($result->getMatchedRoute()); // Mezzio\Router\Route
Eşleşen rota adını almanızı sağlar. Bu sonuç başarısız ise, false değerine; aksi takdirde, eşleşen rota adına döner.
echo $result->getMatchedRouteName(); // /api/auth/token^POST
Eşleşen rota parametrelere geri döner. Parametre boş bile olsa bir dizi dönmek garanti edilir.
print_r(array_keys($result->getMatchedParams())); // Array ([0] => middleware)
Bu rota eşleşmesi başarısız ise true değerine geri döner.
var_dump($result->isFailure());
// false
Sonuç, HTTP yöntemi nedeniyle yönlendirme başarısızlığı varsa false değerine geri döner.
var_dump($result->isMethodFailure());
// false
Bu rota için izin verilen yöntemlere geri döner.
print_r($result->getAllowedMethods()); // Array ([0] => POST)
Daha fazla bilgi için https://docs.mezzio.dev/mezzio/v3/features/router/intro/ adresini ziyaret edebilirsiniz.