squidit / slim-attribute-router
Slim (v4) Framework - Attribute Router
Requires (Dev)
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2024-10-21 10:21:19 UTC
README
Attribute Action/Controller router
This package allows you to add routes to your slim4 (https://www.slimframework.com) application using attributes in your action classes.
Features
- Route Method support
- Route name support
Attribute signature
#[Route({route}[[, {methods}], {routeName}])]
Adding Attribute to an ActionController
If you want to add a route using attributes you can accomplish this by adding a #[Route({route}[[, {methods}], {routeName}])]
route tag to your class method. please see examples:
Example
web address test 1: https://server.name/test1/http/202
<?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; class StatusCodeAction { #[Route('/test1/http/{statusCode:[1-5]{1}\d{2}}',['GET', 'POST', 'PUT', 'DELETE'], 'test_http_statuscode')] public function __invoke(Request $request, Response $response, array $args): Response { // action/controller code return $response; } }
Examples without a 'name' parameter
web address test 2: https://server.name/test2/http/202
web address test 3: https://server.name/test3/http/202
<?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; class StatusCodeAction { #[Route('/test2/http/{statusCode:[1-5]{1}\d{2}}',['POST'])] public function testMethod2(Request $request, Response $response, array $args): Response { // action/controller code return $response; } #[Route('/test3/http/{statusCode:[1-5]{1}\d{2}}',['DELETE'])] public function testMethod3(Request $request, Response $response, array $args): Response { // action/controller code return $response; } }
- The methods parameter is required when writing the Route attribute
- The path to your ActionController files needs to be specified when instantiating the attribute router
Installation
This package can be installed using Composer
Navigate into your project's root directory and execute the bash command shown below
composer require squidit/slim-attribute-router
Enabling the Attribute Router
Our attribute router extends slims default RouteCollector, so we can just instantiate our attribute router and pass it on to our AppFactory
<?php use SquidIT\Slim\Routing\AttributeRouteCollector; use Slim\Factory\AppFactory; // create AttributeRouteCollector $attributeRouteCollector = new AttributeRouteCollector([ 'path' => [ '/path/to/ActionControllers', '/different/path/to/ActionControllers/if/needed', ]], AppFactory::determineResponseFactory(), new CallableResolver($container) // pass in your DI container if you are using a container ); // Instantiate the app AppFactory::setRouteCollector($attributeRouteCollector); $app = AppFactory::create(); $app->run();