Giter VIP home page Giter VIP logo

slim-annotations-router's Introduction

Latest Stable Version Total Downloads Latest Unstable Version License

Slim Annotations Router

Controller and annotations based router for Slim Framework V3

Installation

Via Composer :

composer require ergy/slim-annotations-router

Initialization

To initialize the annotations router, simply add this lines to your index.php file that loads your Slim application :

$app = new \Slim\App();
$c = $app->getContainer();
$c['router'] = function() use ($app) {
  return new \Ergy\Slim\Annotations\Router($app,
    '/path_to_controller_files/', // Path to controller files, will be scanned recursively
    '/path_to_cache_files/' // Path to annotations router cache files, must be writeable by web server, if it doesn't exist, router will attempt to create it
  );
};

If your application contains controllers in multiple folders, you can add them by passing an array in the second parameter to the constructor instead of a string, eg :

return new \Ergy\Slim\Annotations\Router($app,
  ['/path_to_controller_files_1/', '/path_to_controller_files_2/', ...],
  '/path_to_cache_files/'
);

Controller files

The annotations router detects all files with names ending in "Controller.php" and all public methods with names ending in "Action". It then parses their annotations to generate routes recognized by Slim framework.

The following annotations are supported :

Name Level Type Required Description
@RoutePrefix Class string no The route prefix, used for all routes in the current class
@Route Method Object yes The route definition

The @Route object accepts the following syntaxes :

// Route pattern (required), can contain regular expressions
@Route("/home")

// Route methods (optional), if not set only GET route will be generated
@Route("/home", methods={"GET","POST","PUT"})

// Route name (optional), used to generate route with Slim pathFor() method
@Route("/home", methods={"GET","POST","PUT"}, name="home")

Let's see an example :

/**
 * File /my/app/controllers/homeController.php
 * @RoutePrefix("/home")
 */
class HomeController
{
  /**
   * @Route("/hello/{name:[\w]+}", methods={"GET","POST"}, name="home.hello")
   */
  public function helloAction($name)
  {
    echo 'Hello '.$name.' !';
  }
}

By opening the url http://your_site_url/home/hello/foobar, you should see "Hello foobar !".

Get Slim dependency container

Once your controller loaded, you might need to interact with the current HTTP request and response, to get theses objects, your controller simply has to extends the Ergy\Slim\Annotations\Controller class.

Extending this class allows you to retrieve a reference to the Slim dependency container, so to retrieve the current request, you simply have to ask for $this->request.

Let's see an example with the previous class :

/**
 * File /my/app/controllers/homeController.php
 * @RoutePrefix("/home")
 */
class HomeController extends Ergy\Slim\Annotations\Controller
{
  /**
   * @Route("/hello/{name:[\w]+}", methods={"GET","POST"}, name="home.hello")
   */
  public function helloAction($name)
  {
    echo 'Hello '.$name.' !';
    
    // Dump the current request details
    var_dump($this->request);
    
    // Dump the current response details
    var_dump($this->response);
  }
}

Since we have a reference to the Slim dependency container, we can retrieve any object it contains, for example if you want to retrieve the applications settings, simply ask for $this->settings.

Routing events

The annotations router exposes the methods beforeExecuteRoute and afterExecuteRoute.

These methods take as a parameter a Ergy\Slim\Annotations\RouteInfo instance that gives you information about the running route.

Implementing these methods in your controller (or one of its parent classes) allow you to implement hook points before/after the actions are executed.

Example with the previous class :

/**
 * File /my/app/controllers/homeController.php
 * @RoutePrefix("/home")
 */
class HomeController
{
  public function beforeExecuteRoute(Ergy\Slim\Annotations\RouteInfo $route)
  {
    echo 'before ';
  }
  
  public function afterExecuteRoute() // Parameter Ergy\Slim\Annotations\RouteInfo is optional
  {
    echo ' after';
  }
  
  /**
   * @Route("/hello/{name:[\w]+}", methods={"GET","POST"}, name="home.hello")
   */
  public function helloAction($name)
  {
    echo 'Hello '.$name.' !';
  }
}

By opening the url http://your_site_url/home/hello/foobar, you should see "before Hello foobar ! after".

Operation cancellation

Previous hooks allow you to cancel operations if needed :

  • You can cancel execution of current route and afterExecuteRoute method by returning either false or an instance of \Psr\Http\Message\ResponseInterface in the method beforeExecuteRoute.

  • You can cancel the call to afterExecuteRoute method by returning either false or an instance of \Psr\Http\Message\ResponseInterface in the current route method.

For example :

/**
 * File /my/app/controllers/homeController.php
 * @RoutePrefix("/home")
 */
class HomeController
{
  public function beforeExecuteRoute(Ergy\Slim\Annotations\RouteInfo $route)
  {
    echo 'before ';
  }
  
  public function afterExecuteRoute() // Parameter Ergy\Slim\Annotations\RouteInfo is optional
  {
    echo ' after';
  }
  
  /**
   * @Route("/hello/{name:[\w]+}", methods={"GET","POST"}, name="home.hello")
   */
  public function helloAction($name)
  {
    echo 'Hello '.$name.' !';
    return false;
  }
}

By opening the url http://your_site_url/home/hello/foobar, you should see "before Hello foobar !".

slim-annotations-router's People

Contributors

remyjeancolas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

urvishsspl

slim-annotations-router's Issues

Uncaught exception 'ReflectionException'

Error message:
Uncaught exception 'ReflectionException' with message 'Class HomeController does not exist'

Here is my code:

in index.php:

$c['router'] = function() use ($app) {
    return new \Ergy\Slim\Annotations\Router($app,
        THEPATH.'/routes/', // Path to controller files, will be scanned recursively
        THEPATH.'/cache/' // Path to annotations router cache files, must be writeable by web server, if it doesn't exist, router will attempt to create it
    );
};

in routes folder:
homeController.php - contents:

<?php
/**
 * File /my/app/controllers/homeController.php
 * @RoutePrefix("/home")
 */
class HomeController
{
    /**
     * @Route("/hello/{name:[\w]+}", methods={"GET","POST"}, name="home.hello")
     */
    public function helloAction($name)
    {
        echo 'Hello '.$name.' !';
    }
}

Full error as shown by slim:

Uncaught exception 'ReflectionException' with message 'Class HomeController does not exist' in /var/www/clients/client1/web2/web/vendor/ergy/slim-annotations-router/src/Router.php:199
Stack trace:
#0 /var/www/clients/client1/web2/web/vendor/ergy/slim-annotations-router/src/Router.php(199): ReflectionClass->__construct('HomeController')
#1 /var/www/clients/client1/web2/web/vendor/ergy/slim-annotations-router/src/Router.php(147): Ergy\Slim\Annotations\Router->_parseFile('/var/www/client...')
#2 /var/www/clients/client1/web2/web/vendor/ergy/slim-annotations-router/src/Router.php(61): Ergy\Slim\Annotations\Router->_generateRoutes()
#3 /var/www/clients/client1/web2/web/index.php(37): Ergy\Slim\Annotations\Router->__construct(Object(Slim\App), '/var/www/client...', '/var/www/client...')
#4 /var/www/clients/client1/web2/web/vendor/pimple/pimple/src/Pimple/Container.php(113): {closure}(Object(Slim\Container))
#5 /var/www/clients/client1/web2/web/vendor/slim/slim/Slim/Container.php(266): Pimple\Container->offsetGet('r in /var/www/clients/client1/web2/web/vendor/ergy/slim-annotations-router/src/Router.php on line 199

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.