Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Slim Framework: Introducing a New PHP Concept

Slim is light weight PHP framework which is used for developing small and medium scale web applications. In this article we will explore this framework in practice.

What is Slim Framework?

Slim is light weight PHP framework which is used for developing small and medium scale web applications. It is also known as PHP micro framework. Slim has Restful APIs using which we can build simple, secure and effective web application

Typically micro framework provides receiving and routing the HTTP request to a particular controller that returns the HTTP response. Micro framework also has additional tools for manipulating the HTTP response like HTTP caching, redirect, status updates with extensible middleware implementation.

Micro framework mainly deals with the HTTP requests and HTTP responses.

The slim framework was inspired by 'Sinatra' , which is an open source web application written in the Ruby language.

History

PHP is a not modular to develop large scale applications. Slim framework is much better than PHP, which provides simpler programming interface than PHP.

The 'New media campaigns' company sponsors the slim framework for more research and development. The latest version of slim framework is 2.6.1 available in the GitHub website.

Architecture of Slim framework



Architecture of the slim framework

  • The devices such as mobiles, tablets and computers send the HTTP request to the restful APIs. In this case, Restful APIs provide an interface between the database and devices.
  • Restful APIs has the Slim application methods that are used to process the HTTP request sent by the clients.
  • Restful APIs take the HTTP requests from devices and process them in the database.
  • Database looks for the requested data and sends responses back to the devices through Restful APIs as HTTP responses.

.htaccess file contains the code which helps for URL redirection.

Installation

There are two ways to install the slim framework.

1. Composer Install.

2. Manual Install.

Composer installation

* You need to install the composer by using the following command.

curl ?s https://getcomposer.org/install | php

* You need to create a composer.json file in your root directory of server and include the following lines of code into the composer.json file. 2.* is the version of the Slim framework.

{
            ?require?:{
                                   ?Slim/Slim?:?2.*?
                             }
}

* Use the following command to install through composer.

php composer.phar install

* In index.php, add the following lines of code and run the code in your localhost by passing the name parameter in URL.

<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
    echo "hello, $name";
});
$app->run();
?>
                                                        

Manual Installation consist of the following steps

* Download the latest version of slim framework zip file from the following website.

https://github.com/codeguy/Slim/zipball/master

* Extract the zip file to the localhost root directory. It looks like as shown below.

/../www/slimphp/

Note: Don't forget to edit the '.htaccess' file present in the slimphp folder.

Add the following lines of code and save the file

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^ index.php [QSA,L]

* In index.php, add the following lines of code and run the code in your localhost by passing the name parameter in URL.

<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
    echo "hello, $name";
});
$app->run();
?>
                                          

Features of Slim Framework


* Slim Framework application is simple and easy to configure.

* If you have a brief knowledgeabout the HTTP protocols, then it is easy to use and code the web application using Slim application.

* Slim framework has powerful routes such as:

o Route middleware.

o Route redirect.

o Standard HTTP methods.

* Simple to solve the errors and easy to fix.

* It uses AES-256 encryption mechanism to secure the data which is stored in cookies.

* You can also render external PHP files in your code by using the template rendering.

* HTTP caching.

* It is simple to display the flash messages in the Slim application by using flash() and flashNow() methods.

Example

The following is a simple example which shows hello world message on your browser.

Listing 1: helloworld.php

<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
    echo "hello, $name";
});
$app->run();
?>

Details of the code

* The line 'require 'Slim/Slim.php''; includes the Slim.php file which extracts the built-in Slim application methods.

* registerAutoloader() method is used to register the Slim auto loader functions.

* You need to create the object of Slim class i.e. $app which helps to access the contents of Slim.php file.

* The get() method is used to function the resources URI which are requested through HTTP GET method. It has name as a parameter and a callable function($name) to display the name value on your browser.

* Finally you need to call the run() method as '$app->run()' to execute your code.

Output

* Save the file as hellworld.php.

* Open the web browser and type localhost/slimphp/helloworld.php/hello/world

* world is the value for the name attribute.

Figure 1: Helloworld Example

Routing

The Slim application uses the HTTP request methods such as GET, POST, PUT, DELETE, OPTIONS or HEAD as callback function. Let us discuss these methods one by one.

GET Route

The Slim Application get() method retrieves the information from the URI, sent by a client using HTTP GET request. HTTP GET only retrieves the data and does not modify or alter the data.

Following code format shows how to make use of the get() method.

Listing 2: get_route.php

<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/hi/:name', function($name) {
 echo "hi, $name";
});
$app->run();
?> 

As shown in the code, we are sending the argument through HTTP GET request as /hi/Manu. This value is send back to the callable function($name) to display the sent value of name on your browser.

Output

* Save the file as get_route.php.

* Open the web browser and type localhost/slimphp/ get_route.php/hi/Manu

* Manu is the value for the name attribute.

Figure 2: get_route Example


POST Route

The Slim Application post() method sends the information to the server. For example photo upload, user details, application form etc using the form.

Following example shows how to make use of the post() method.

Listing 3:post_.html

<!DOCTYPE html>
<html>
<body>
<form action="post_route.php" method="post">
Enter the name of bag:<br>
<input type="text" name="bags">
<br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html> 


Listing 4: post_route.php

<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$paramValue1 = $app->request->post('bags');
echo '<b>'.$paramValue1.'<br>';
?>

As shown in the code of post_.html, we are sending argument through HTTP POST request using HTML form. This value is sent back to the callable function() to display the sent value of bags on your browser.

Output

* Save the HTML file as post_.html and the PHP file as post_route.php

* Open the web browser and type localhost/slimphp/post_.html

* Enter the value in the text box and submit the value. You will get the result as shown in the below screen shot Figure 4.

Figure 3: post_html Example

Figure 4: post_route Example

PUT Routes

The Slim Application put() method replaces the stored information by newly uploaded data using HTTP PUT request.

<?php
$app = new \Slim\Slim();
$app->put('/student/:roll', function ($roll) {
    //Update the student info by $roll
});
?>

The above code describes how to update the student information by using the roll value. This can be done using put() method of the slim application. In put() method, you should pass the roll value to update the particular student information.

DELETE Route

The Slim Application delete() method removes the information given by a URI and URI request is sent by a client using HTTP DELETE request.

<?php
$app = new \Slim\Slim();
$app->delete('/student/:roll', function ($roll) {
    //Delete the student info by $roll
});
?>
 

The above code describes how to remove the student information by using the roll value. This can be done by using the delete() method of the slim application. In the delete() method, you should pass the roll value to remove the particular student information.

Rests of the HTTP methods PATCH, OPTION are also used to deal with the respective HTTP methods.

Route Parameter


In route parameter, you can pass two or more values to the resource URI.

The below example describes the use of route parameter.

Listing 5: route_parameter.php

  <?php
  require 'Slim/Slim.php';
  \Slim\Slim::registerAutoloader();
  $app = new \Slim\Slim();
  $app->get('/name/:name/lname/:lname/mobnum/:num',                                  function ($name,$lname,$num) {
      echo "$name $lname $num";
  });
  $app->run();
  ?>
  

In the above code we are passing three values to the resource URI as name, lname and num.

Output

* Save the file with name route_parameter.php

* Open the web browser and type localhost/slimphp/route_parameter.php/name/Manu/lname/kumbar/mobnum/8792227920

Figure 5: route_parameter Example


Route Names

Route Names assign a name to a route which generates URLs dynamically using urlFor() helper method. You can freely change route patterns without effecting your application.

The below example generates URLs for route and name() is a chainable method.

Listing 6: route_name_url.php

<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
//Create a named route
$app->get('/hello/:name', function ($name) use ($app) {
    //echo "hello $name";
})->name('hello');
//Generate a URL for the named route
$url = $app->urlFor('hello', array('name' => 'Manu'));
echo $url;
$app->run();
?> 

As shown in the above example, the urlFor() method replaces the route's URL parameter world with the specified values in the urlFor() method i.e. Manu. In this case the array's key value must match with the URL of route.

Output

* Save the file with name route_name_url.php

* Open the web browser and type localhost/slimphp/route_name_url.php/hello/world

Figure 6: route_name_urlFor Example


Route Conditions

It is the same as a pattern matching mechanism which returns the value if the passed URI argument matches the condition or else gives an error message.

$app->get('/num/:num',function($num){    
//code goes here
 })->condition(array('num'=>(10|30));

The above code shows regular expression for num. The num must be greater than 10 and less than 30.

Route Middleware

The Slim application route middleware always returns true for each is_callback() method. To add route middleware we should invoke the route pattern and callable so that matches an HTTP request.

You can also define separate middleware methods as follows.


Function addmw1(){
Echo ?This is addmiddleware1?;
}
Function addmw2()(){
Echo ?This is addmiddleware2?;
}
$app=new \Slim\Slim();
$app->get('/foo',' addmw2',' addmw2',function(){
//code goes here
});    

In the above code /foo route is invokes the addmw1 and addmw2 functions in sequence before the route's callable is invoked. You can also pass the parameter to the middleware.

Route Groups

Route group helps to group the related routes such as get(), put(), delete(), post().

Route Helpers

It helps to control flow of our application. It contains helper methods such as halt(), pass(), redirect(), stop() which are implemented using exception.

Route URI Rewriting

URL rewriting helps to maintain human-friendly URLs with the Slim application. You should use the appropriate tool that is provided by the web browser to enable URL Rewriting.

Environment Variable

Environment variables associates array of settings. You can modify the environment variables at the run time of an application. Environment variables are derived from the $_SERVER superglobal. In a Slim application, environment variables are parsed only once and also describe how the Slim application runs; HTTP methods, HTTP Request body, resource URI, error output, URL parameter and more.

Following are the Environment Variables used in Slim framework

* REQUEST_METHOD

* SCRIPT_NAME

* PATH_INFO

* QUERY_STRING

* SERVER_NAME

* SERVER_PORT

* HTTP_*

* slim.url_scheme

* slim.input

* slim.errors


Request Overview

Using request object, you can easily interact with the Slim application environment variables. It is an abstraction of the HTTP request and the Request object is defined in \Slim\Http\Request.

$rq=$app->request;

The above line returns the instance of \Slim\Http\Request.


Request Method

Current HTTP request can be obtained by using the request object and returns Boolean.

$app->request->isGet();
$app->request->isPost();
$app->request->isDelete();
$app->request->isHead();
$app->request->isPatch();
$app->request->isOption();
$app->request->isAjax();


Request Header

The header property provides a simple interface for the HTTP request. The Slim application automatically parses an HTTP request header. HTTP headers may be in uppercase or lower case or mixed case, which the Slim application can parse without any difficulties.

$app=new \Slim\Slim();
$headers=$app->request->headers;
$getcharset=$app->request->headers->get('ACCEPT_CHARSET');

The above code gets the 'ACCEPT_CHARSET' header.


Request Body

The getBody() method fetch the HTTP request body sent by the HTTP client.

$body=$app->request->getBody();
//getBody() to fetch HTTP request


Request Variable

It helps to get the parameters sent by the particular HTTP methods like GET, POST, and PUT. param() method accesses the parameters without considering the type of the variables and you can also use particular get(), post() and put() methods of HTTP request.

require 'Slim/Slim.php';
$app = new \Slim\Slim();
$paramValue1 = $app->request->param('param');
$paramValue2 = $app->request->param('param');

The above code requests the value, if the value exists then param() method returns the value or else returns null.

require 'Slim/Slim.php';
$app = new \Slim\Slim();
$paramValue1 = $app->request->get('param');
$paramValue2 = $app->request->post('param');
$paramValue2 = $app->request->put('param');
 

The above code returns null if value does not exist. And it uses the different HTTP methods.


Request Cookies

Cookies are plain text files that contain information such as user log and browsing history etc. The Slim application getCookie() method helps to fetch the cookie values.


Cookie Encryption

In the Slim application Cookies are encrypted to keep the data confidential and secure. Cookies are encrypted using secret key and cipher. Decrypt using \Slim\Slim::getCookie() method.

The below code shows how to store a cookie:

Listing 7: cookieexample.php

<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/', function () use ($app) {
$app->setCookie('setcookie', 'mycookie');
 
   echo $app->getCookie('setcookie');
   echo '<br/>';
   echo \Slim\Slim::getInstance()->getCookie('setcookie');
});
$app->run();
?>

Details of the code

* $app->setcookie() method is used to set the 'mycookie' value to the 'setcookie'.

* The get() method helps to display the cookie values.

* The getCookie() method helps to get the cookie values.

* \Slim\Slim::getInstance()->getCookie('setcookie') create an instance of the Slim class.


Output

* Save the file with name ex.php

* Open the web browser and type localhost/slimphp/ex.php

Figure 7: Cookie


Response Overview

Response object abstracts the HTTP response that is sent by the client. The response object is defined in \Slim\Http\Response. The Slim instance has one response object.

Format of response object is as follows:

$app = new \Slim\Slim();
$app->response;

Properties of HTTP response are:

1. Status

The status contains the set of codes that represent the different values. For example, 200 return OK, 400 return Bad request and 500 represent server error.


2. Header

Each HTTP client has a Header, which contains the key and value pairs to provide the metadata of the HTTP response. The response object has a header and it is instance of the \Slim\http\set.


3. Body

HTTP body contains the actual code of HTTP response that is delivered to the HTTP client.


Response Cookies

Set Cookie

The Slim application HTTP response set the cookie values using setCookie() method.

$app->setCookie('setcookie', 'mycookie');

The above line set the mycookie value for setcookie attribute. You can also delete the cookies using deleteCookie() method.

$app->deleteCookie('setcookie');


Views

View is used for rendering the templates. View is a subclass of \Slim\View. The \Slim\View implements the interface.

Rendering

render() method includes the current view object, that render templates with given set of variables. render() method will echo() the output return from the view object.

$app = new \Slim\Slim();
$app->get('/name/:name', function ($name) use ($app) {
    $app->render('template.php', array('name' => $name));
});

The above code describes:

* Render() method includes the content of the template.php file.

* Render() return the value of name as array format ?name?:?name?.

Below code shows the Viewer class that extends the View interface.

class Viewer extends \Slim\View
{
    public function render($template)
    {
// code goes here
    }
}

HTTP caching

HTTP caching has etag(), lastModified(), and expires() helper methods. You can use any one of the etag(), lastModified() method with an expires().

The etag() method is unique identifier for a resource URI. Both etag() and lastModified() instruct an HTTP client to store the resource response in a client-side cache. The expires() method indicates to the HTTP client when the client-side cache should be considered stale.

HTTP client sends 'If-None-Match' message, if it is not found.

$app->get('/foo', function () use ($app) {
    $app->etag(id');
    });

In the above code, etag() method ensures that each client has a unique ID. lastModified() method is used to get the last modified date and time of the HTTP client. If last modified date is altered, then lastModified() method return true else return the 304 Not Modified.

$app->get('/foo', function () use ($app) {
    $app->lastModified(123456779);
});

The above code determines the last modified data and time.

Middleware Architecture

Slim application middleware is used to analyze, modify the environment, requests and responses after a Slim application is included. The middleware architecture has an run() method that is included in every program of the Slim application. The middleware class is defined in the \Slim\Middleware and you need to extend the middleware class when required.

The below code shows how to extend the Middleware class of Slim application:

class MyMiddle extends \Slim\Middleware
{
    public function call()
    {
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();        
        $env = $app->environment; //The Environment object
                $req = $app->request; //The Request object
 
 
        $res = $app->response;        //The Response object
    }
}


Hooks Overview

Hooks are used to register your own callback. Hook is the moment in the slim framework that helps to get priority list of callback that is assigned to the hook. Hook is a recognized by a string. The callable can return true or is_callable() method. You can also pass multiple callables to a hook by using hook() method.

$app = new \Slim\Slim();
$app->hook('hookname', function () {
    //code goes here
});

The hook() method takes hookname as argument and second argument is the callable function. Each of the hook() method contains the priority list registered callback. In this case hook does not pass the argument to their callable. You can also give a callable different priorities by passing integer as a third argument to the hook() method.

Default Hooks

Slim.before

This hook is invoked before output buffer turned on and before the Slim application run.

Slim.before.router

This hook is invoked after output buffering is turned on and before the router is dispatched.

slim.before.dispatch

This hook is invoked before the current matching route is dispatched.

slim.after.dispatch

This hook is invoked after the current matching route is dispatched.

slim.after.router

This hook is invoked after the router is dispatched, before the Response is sent to the client, and after output buffering is turned off.

slim.after

This hook is invoked after output buffering is turned off and after the Response is sent to the client.

Flash Messages

This is one of the nice features of the Slim application that helps displaying the flash messages. Session is required to enable the flash messages. You need to use \Slim\Middleware\SessionCookie middleware to enable the flash message.

Slim application supports two methods that help displaying the flash message i.e.

* flash()

* flashNow()

These two methods accept two arguments in which one is the key and another is a message. The key may be any value that accesses the message in your view template. These flash messages are usually stored as data in the view object.

flash('key1', 'The key1 message');
To display flash message in your view template use the following code
flash['key1'];

The above code is used to display the flash messages. The flash() method take the two argument in our code key and message as 'key1' and 'The key1 message'.

Flash keep

In this case, the Slim application stores the previously generated flash messages for further use in the view template and make them available at the next request.

$app->flashKeep();


Session

Native session store

You can use native PHP session session_start() method before instantiating Slim application.

Cookie Session Store

To enable the session cookie middleware you must use \Slim\Middleware\SessionCookie middleware class. HTTP cookies are limited in storage i.e. 4kb. If encrypted session data exceeds 4kb, then you need to store the cookies in some other local storage.

Logging

Slim application has log object that is used to write data to a specific output. It's very difficult to write data for log writer manually.

You can Log the data as follows

//Get the log object reference
$app = new \Slim\Slim();
$log=$app->log; 

Interfaces for the log object are as follows

$app->log->debug(mixed $object);

$app->log->info(mixed $object);

$app->log->notice(mixed $object);

$app->log->warning(mixed $object);

$app->log->error(mixed $object);

$app->log->critical(mixed $object);

$app->log->alert(mixed $object);

$app->log->emergency(mixed $object);

Each of the interfaces takes argument as mixed. The log object passes argument to the log writer. You need to use slim application log in your program as \Slim\Log.

Slim application provides enabling and disabling logging as follows

//Enable logging
$app->log->setEnabled(true);
//Disable logging
$app->log->setEnabled(false);
$app = new Slim(array(
    'log.enabled' => true
));

Log Levels

\Slim\Log::EMERGENCY

Level 1

\Slim\Log::ALERT

Level 2

\Slim\Log::CRITICAL

Level 3

\Slim\Log::ERROR

Level 4

\Slim\Log::WARN

Level 5

\Slim\Log::NOTICE

Level 6

\Slim\Log::INFO

Level 7

\Slim\Log::DEBUG

Level 8

Log Writer

The log writer is responsible for sending the logged message to the particular output. Slim application also has the log writer class \Slim\LogFileWriter. Examples for log are STDERR and log file. You can also use the custom log writer to specify it in the Slim applications log object.

$app = new \Slim\Slim(array(
    'log.writer' => new MyLogWriter()
));

The above code shows the custom log writing.

Error Handling

It is important to handle the errors in the code. The Slim application has its own methods that are used to manage the errors in the code. The Slim application helper method helps to respond to the errors and exception.

The Slim application only handles the errors that are generated within the application. Error_reporting is used in existing Slim application to report the errors generated in the current code. The Slim application's errors are converted into the errorException object to throw. You need to enable the debug setting to true to handle errors itself by slim application.

Error Handler

Slim application has error() and notFound() method to handle the errors. Both error() and notFound() method is used as setter and getters in Slim. The notFound() method handles the custom messages.

$app = new \Slim\Slim();
$app->notFound(function () use ($app) {
    $app->render('404.html');
});


Dependency Injection

Slim application has a built in resource locator that provides an easy way to inject the object in to the Slim.

$app = new \Slim\Slim();
$app->foo = 'bar';

The above code shows simple way to inject the values into the object.

Resource Locator

You can also use the resource locator to inject values into the Slim application object.

$app = new \Slim\Slim();
// Determine method to create UUIDs
$app->uuid = function () {
    return exec('uid');
};
// Get a new UUID
$uuid = $app->uuids;
                                                                                                                                                                                                                                                                                                                                                                                                                                              

Conclusion


This article has given you a brief glimpse of Slim Framework and its features. The article covered architecture, Installation, Slim features, Routing, Environment Variable, Request Overview, Response Overview, Views, HTTP caching, Middleware Architecture, Hooks Overview, Flash Messages, Session,Logging, and Dependency Injection.

The source code is attached to this article. You can check more information about this nice framework on the official website: http://docs.slimframework.com/



I''m a full stack developer with around 10+ yrs of experience. I enjoy writing technical articles on upcoming technical trends.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login