Annotation Router for Slim 4.x
It's recommended using Composer to install Slim Annotation Router.
$ composer require "nicc0/slim-annotation-router"
This will install Slim Annotation Router and all required dependencies. Remember Slim 4.x requires PHP 7.1 or newer.
$factory = new DecoratedResponseFactory( new ResponseFactory(), new StreamFactory() );
$resolver = new CallableResolver();
$controllerPath = './app/controllers/';
$collector = new AnnotationRouteCollector( $factory, $resolver, $container );
$collector->setDefaultControllersPath( $controllersPath );
$collector->collectRoutes();
$app = new App( $factory, $container, $resolver, $collector );
/**
* Class ExampleController
*
* @RoutePrefix("/example")
*/
class ExampleController
{
/**
* @Route("/hello", methods={"GET"}, name="example.hello")
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function hello(): ResponseInterface
{
$response = new Response();
$response->getBody()->write('Hello world!');
return $response;
}
}
By opening the url http://your_site_url/example/hello, you should see "Hello world!".
To add Middleware to Controller or Action use @Middleware("")
annotation, which pass the name of Middleware.
It is important to know that the name we pass must be defined in the Container. Name passes as the third parameter in the AnnotationRouteCollector
constructor. It is also important that the added Middleware must implements of MiddlewareInterface
otherwise Middleware will not be added to the Route.
There is also possibility to add more than one Middleware to Controller or Action.
For example, we have to add AuthMiddleware to controller. Firstly we have to define AuthMiddleware in Container.
$container->set('authMiddleware', function() use ($container) {
return new AuthContainer(container);
})
If Middleware exists in our Container, now we can use middleware annotation by adding @Middleware("authMiddleware")
to controller.
/**
* @RoutePrefix("/example")
* @Middleware("authMiddleware")
*/
class ExampleController
{
/**
* @Route("/hello", methods={"GET"}, name="example.hello")
*/
public function hello(): ResponseInterface
{
...
}
}
To execute the test suite, you'll need to install all development dependencies.
git clone https://github.com/Nicc0/Slim-Annotation-Router
composer install
composer test
The Slim Annotation Router is licensed under the MIT license. See License File for more information.