Saturday, 15 October 2016

Api routing in slim framework 3

Slim framework router component allows to define routes that are mapped to callback handlers which receive the request. The Slim Framework’s router is built on top of the nikic/fastroute component, and it is remarkably fast and stable. A router simply parses a URI to determine the request and gives appropriate response to it.If you are new to slim framework then read this post also getting started with slim.

Slim framework


Slim get request: 

<?php
require __DIR__ . '/../vendor/autoload.php';
$appObj = new \Slim\App();
$appObj->get('/', function($request, $response) {
      $response->write("welcome to slim");
      return $response;
});
$appObj->run();

The Slim Framework provides methods for the most popular HTTP methods.

$appObj->get() - It handles only GET HTTP requests 
$appObj->post() - It handles only POST HTTP requests 
$appObj->put() - It handles only PUT HTTP requests 
$appObj->patch() - It handles only PATCH HTTP requests 
$appObj->delete() - It handles only DELETE HTTP requests 
$appObj->options() - It handles only OPTIONS HTTP requests 
$appObj->map(['get', 'post']) 

How to define Dynamic routes in slim:

$appObj->get('/hello/{name}',
   function($request, $response, $args) {
           $name = $args['name'];
           return $response->write("Hello $name");
});

How to maintain Regex in Routes in slim:

$appObj->get('/user/{id:\d+}', $callable);
     $appObj->get('/hello/{name:[\w]+}', $callable);
     $appObj->get('/hello{a:/{0,1}}{name:[\w]*}', $callable);
     <h3>Route groups</h3>
     $appObj->group('/books', function () use ($app) {
     $appObj->get('', function ($req, $res) {
            // Return list of records
     });
     $appObj->post('', function ($req, $res) {
            // Create a new record
     });
     $appObj->get('/{id:\d+}', function ($req, $res, $args) {
           // Return a single record
     });
     $appObj->put('/{id:\d+}', function ($req, $res, $args) {
            // Update a record
     });
});

How to maintain Named routes in slim:


// Name the route
$appObj->get('/hello/{name}', function(...) {...})
->setName('hi');
 
// build link:
$link = $appObj->router->urlFor('hi', ['name' => 'John']);
creates: /hello/John

Please feel free to comment below for suggestions and problems.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts