Slim Framework is a tiny framework that assists us with the development of REStful web services in PHP. The growing popularity of web applications that include multiple clients implementations (hybrid and native applications for touch screen devices, hybrid and native applications for desktops and one page websites) require us to implement our server side as a REStful web services application. Using the Slim Framework is one of the simplest yet powerful alternatives.

The following code sample shows how simple it is to use this framework in the development of a simple REStful web service.

<?php
namespace Com\LifeMichael\Samples;
require 'Slim/Slim.php';

\Slim\Slim::registerAutoloader();
$application = new \Slim\Slim();

$application->get(
    '/hello/:firstname/:lastname',
    function ($first,$last)
    {
        echo "Hello $first $last";
    });

$application->run();
?>

The following video clip overviews this code sample, shows its execution and explains each and every part of it.

Though the framework itself is very simple to use, the flexibility it provides us with set it as one of my favorites. The following code sample shows how simple it is to handle multiple HTTP methods using the same route.

The following is the HTML file through which we simulate HTTP GET and HTTP POST requests.

<!DOCTYPE html>
<html>
<head>
    <title>Multiple Methods Routing Demo</title>
</head>
<body>
    <form action="multiplemethodsroute.php/products"
          method="POST">
        product id <input type="text" name="id"/>
        <br/>
        <input type="submit"/>
    </form>
</body>
</html>

The following is the PHP file that handles the HTTP requests coming from the web form, whether they arrived using GET or POST. Going over the code you will also notice the request property the Slim object has. It is one of many other properties that provide us with the flexibility to tweak the web service we develop to work in according to our needs.

<?php

namespace Com\LifeMichael\Samples;

require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();

$application = new \Slim\Slim();

$application->map(
    '/products(/:id)',
    function ()
    {
        global $application;
        $id = $application->request->get('id');
        if($id==null)
        {
            $id = $application->request->post('id');
        }
        echo "showing info about product #".$id;
    })->via('GET','POST');

$application->run();

?>

The following video clip overviews this code sample, shows its execution and explains each and every part of it.

You can find more video clips, code samples and training material for learning how to use this magnificent framework in my online free courses website at http://abelski.lifemichael.com.

 

Leave a Reply

Your email address will not be published. Required fields are marked *