PHP code example of juliangut / slim-routing

1. Go to this page and download the library: Download juliangut/slim-routing 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/ */

    

juliangut / slim-routing example snippets




use Jgut\Slim\Routing\AppFactory;
use Jgut\Slim\Routing\Configuration;
use Jgut\Slim\Routing\Response\PayloadResponse;
use Jgut\Slim\Routing\Response\RedirectResponse;
use Jgut\Slim\Routing\Response\ResponseType;
use Jgut\Slim\Routing\Response\Handler\JsonResponseHandler;
use Jgut\Slim\Routing\Response\Handler\RedirectResponseHandler;
use Jgut\Slim\Routing\Strategy\RequestHandler;
use Psr\Http\Message\ServerRequestInterface;

$configuration = new Configuration([
    'sources' => ['/path/to/routing/files'],
]);
AppFactory::setRouteCollectorConfiguration($configuration);

// Instantiate the app
$app = AppFactory::create();

$routeCollector = $app->getRouteCollector();
$responseFactory = $app->getResponseFactory();

// Register custom invocation strategy to handle ResponseType objects
$invocationStrategy = new RequestHandler(
    [
        RedirectResponse::class => new RedirectResponseHandler($responseFactory, $routeCollector),
        // Handlers can be pulled from the container
        PayloadResponse::class => JsonResponseHandler::class,
    ],
    $responseFactory,
    $app->getContainer()
);
$routeCollector->setDefaultInvocationStrategy($invocationStrategy);

$cache = new PSR16Cache();
$routeCollector->setCache($cache);

// Recommended if you want to add more routes manually
$routeCollector->registerRoutes();

// Additional routes if needed
$app->get('/', function(ServerRequestInterface $request): ResponseType {
    return new PayloadResponse(['param' => 'value'], $request);
});

$app->run();

$app->get('/hello/{name}', function (ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface {
    return $this->view->render(
        $response,
        'greet.html',
        [
            'name' => $args['name']
        ]
    );
})->setName('greet');

$app->get(
    '/hello/{name}', 
    fn (array $args): string => 'Hello ' . $args['name'],
)->setName('greet');

use Jgut\Slim\Routing\Response\ResponseType;
use Jgut\Slim\Routing\Response\ViewResponse;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

$app->get(
    '/hello/{name}', 
    fn (ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseType 
        => new ViewResponse('greet.html', ['name' => $args['name']], $request, $response),
)->setName('greet');

use Jgut\Slim\Routing\Response\PayloadResponse;
use Jgut\Slim\Routing\Response\Handler\JsonResponseHandler;

$invocationStrategy->setResponseHandler(PayloadResponse::class, JsonResponseHandler::class);

use Jgut\Slim\Routing\Transformer\ParameterTransformer;
use Slim\Exception\HttpNotFoundException;

final class UserEntityTransformer implements ParameterTransformer
{
    public function __construct(
        private EntityManager $entityManager,
    ) {}

    protected function supports(string $parameter, string $type) : bool
    {
        return $parameter === 'user' && $type === UserEntity::class;
    }

    protected function transform(string $parameter, string $type, mixed $value): mixed
    {
        $user = $this->entityManager->getRepository($type)->find($value);
        if ($user === null) {
            throw new HttpNotFoundException('User not found');
        }

        return $user;
    }
}

use Symfony\Component\Console\Application;
use Jgut\Slim\Routing\Console\ListCommand;
use Jgut\Slim\Routing\Console\MatchCommand;

/** @var \Slim\App $app */
$routeResolver = $app->getRouteResolver();

$cli = new Application('Slim CLI');
$cli->add(new ListCommand($routeResolver));
$cli->add(new MatchCommand($routeResolver));

$app->run();

use Jgut\Slim\Routing\Mapping\Attribute\Group;

#[Group(
    prefix: 'routePrefix',
    parent: Area::class,
    pattern: 'section/{section}',
    placeholders: ['section': 'alpha'],
    arguments: ['scope' => 'public'],
 )]
class Section {}

use Jgut\Slim\Routing\Mapping\Attribute\Route;

class Section
{
    #[Route(
        name: 'routeName',
        methods: ['GET', 'POST'],
        pattern: 'user/{user}',
        placeholders: ['user': 'alnum'],
        arguments: ['scope': 'admin.read']
        xmlHttpRequest: true,
        priority: -10,
    )]
    public function userAction() {}
}

use Jgut\Slim\Routing\Mapping\Attribute\Group;
use Jgut\Slim\Routing\Mapping\Attribute\Middleware;
use Jgut\Slim\Routing\Mapping\Attribute\Route;
use Psr\Http\Message\ResponseInterface;

#[Group()]
#[Middleware(GroupMiddleware::class)]
#[Middleware(AdditionalMiddleware::class)]
class Section
{
    #[Route(methods: ['GET'], pattern: 'user')]
    #[Middleware(RouteMiddleware::class)]
    public function userAction(): ResponseInterface {}
}

use Jgut\Slim\Routing\Mapping\Attribute\Group;
use Jgut\Slim\Routing\Mapping\Attribute\Route;
use Jgut\Slim\Routing\Mapping\Attribute\Transformer;
use Psr\Http\Message\ResponseInterface;

#[Group()]
#[Transformer(transformer: SectionEntityTransfomer::class)]
class Section
{
    #[Route(methods: ['GET'], pattern: 'user/{user}')]
    #[Transformer(
        transformer: UserEntityTransfomer::class),
        parameters: ['user': User::class],
    )]
    public function userAction($request, $response, $user): ResponseInterface {}
}

return [
  [
    // Group
    'prefix' => 'prefix',
    'pattern' => 'group-pattern',
    'placeholders' => [
        'group-placeholder' => 'type',
    ],
    'arguments' => [
        'group-argument' => 'value',
    ],
    'parameters' => [
        'group-parameters' => 'type',
    ],
    'transformers' => ['group-transformer'],
    'middlewares' => ['group-middleware'],
    'routes' => [
      [
        // Route
        'name' => 'routeName',
        'xmlHttpRequest' => true,
        'methods' => ['GET', 'POST'],
        'priority' => 0,
        'pattern' => 'route-pattern',
        'placeholders' => [
            'route-placeholder' => 'type',
        ],
        'parameters' => [
            'route-parameters' => 'type',
        ],
        'transformers' => ['route-transformer'],
        'arguments' => [
            'route-argument' => 'value',
        ],
        'middlewares' => ['route-middleware'],
        'invokable' => 'callable',
      ],
      [
        // Subgroup
        'pattern' => 'subgroup-pattern',
        'placeholders' => [
            'subgroup-placeholder' => 'type',
        ],
        'arguments' => [
            'subgroup-argument' => 'value',
        ],
        'middlewares' => ['subgroup-middleware'],
        'routes' => [
          // Routes/groups ...
        ],
      ],
      // Routes/groups ...
    ],
  ],
  // Routes/groups ...
];

use Jgut\Slim\Routing\Mapping\Annotation as JSR;

/**
 * @JSR\Group(
 *     prefix="routePrefix",
 *     parent=Area::class,
 *     pattern="section/{section}",
 *     placeholders={"section": "[a-z]+"},
 *     arguments={"scope": "public"}
 *     parameters={"section": "\Namespace\To\Section"},
 *     transformers={"\Namespace\To\GroupTransformer"}
 *     middleware={"\Namespace\To\GroupMiddleware"}
 * )
 */
class Section {}

use Jgut\Slim\Routing\Mapping\Annotation as JSR;

class Section
{
    /**
     * @JSR\Route(
     *     name="routeName",
     *     xmlHttpRequest=true,
     *     methods={"GET", "POST"},
     *     pattern="user/{user}",
     *     placeholders={"user": "[a-z0-9]+"},
     *     arguments={"scope": "admin.read"}
     *     parameters={"user": "\Namespace\To\User"},
     *     transformers={"\Namespace\To\RouteTransformer"},
     *     middleware={"\Namespace\To\RouteMiddleware"},
     *     priority=-10
     * )
     */
    public function userAction() {}
}
bash
php -f cli.php slim:routing:list --help
bash
php -f cli.php slim:routing:match --help