PHP code example of tarikweiss / slim-attribute-router

1. Go to this page and download the library: Download tarikweiss/slim-attribute-router library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tarikweiss / slim-attribute-router example snippets


$router = new \Tarikweiss\SlimAttributeRouter\Router(
    ['/path/to/project/src/Action'],
    new \Tarikweiss\SlimAttributeRouter\PublicMethodRouteTargetCreator('run')
);

/** @var \Slim\App $slimApp */
$router->registerRoutes($slimApp);


#[\Tarikweiss\SlimAttributeRouter\Route(
    methods: ['GET', 'POST'],
    path: '/foo'
)]
class FooAction
{
    /**
     * Here the name given in the constructor of the PublicMethodRouteTargetCreator is used.
     */
    public function run(
        \Psr\Http\Message\ServerRequestInterface $request,
        \Psr\Http\Message\ResponseInterface      $response,
        array                                    $arguments
    ): \Psr\Http\Message\ResponseInterface {
        // Do you request handling and respond to the request.
        // This structure is given by Slim!
        // Have a look at the docs: https://www.slimframework.com/docs/v4/start/installation.html#step-4-hello-world
        return $response;
    }
    
    
    #[\Tarikweiss\SlimAttributeRouter\Route(
        methods: ['PATCH'],
        path: '/foo'
    )]
    public function anotherActionHandler(
        \Psr\Http\Message\ServerRequestInterface $request,
        \Psr\Http\Message\ResponseInterface      $response,
        array                                    $arguments
    ): \Psr\Http\Message\ResponseInterface {
        // Same structure as above, but different scope.
        return $response;
    }
}
}


class PublicMethodRouteTargetCreator implements \Tarikweiss\SlimAttributeRouter\RouteTargetCreator
{
    public function __construct(
        public string $classLevelMethodName = 'run'
    )
    {
    }


    public function createRouteTarget(\Tarikweiss\SlimAttributeRouter\RouteLevel $routeLevel, string $class, ?string $method): callable|string
    {
        return match ($routeLevel) {
            \Tarikweiss\SlimAttributeRouter\RouteLevel::LEVEL_CLASS  => $class . ':' . $this->classLevelMethodName,
            \Tarikweiss\SlimAttributeRouter\RouteLevel::LEVEL_METHOD => $class . ':' . $method,
        };
    }
}