In some of my last post I explain a various method to creating webservice using various technology.  Now this time I explain another PHP framework which is specially designed to create web services. If you want to create REST API for your mobile application in few minutes then Slim framework is really very helpful for you. To setup slim framework in your server, you can simply use composer. To create REST API in PHP using Slim follow bellow steps.

Step 1. Get a fresh copy of Slim framework using composer or you can manually download from their official website. If you are using composer and your composer install globally then run this command.

composer create-project slim/slim-skeleton my-app

Step 2. After getting latest release of slim framework create index.php file include framework  library as shown bellow 

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';

Step 3. Now initialize slim framework and create connection to your database as shown below

// Setting up database details
$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;

$config['db']['host']   = "localhost";
$config['db']['user']   = "root";
$config['db']['pass']   = "1234567890";
$config['db']['dbname'] = "my_app";

$app = new \Slim\App(["settings" => $config]);

// DB
$container['db'] = function ($c) {
    $db = $c['settings']['db'];
    $pdo = new PDO("mysql:host=" . $db['host'] . ";dbname=" . $db['dbname'],
        $db['user'], $db['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};

Step 4. Now if our database is connected successfully we can create a method to handle the request. You can handle bellow given type of request in Slim

  • GET
  • POST
  • PUT
  • DELETE
  • HEAD
  • PATCH
  • OPTIONS

Now we create our first method you can create a method like this first you get your application $app and after request method like Get/Post as shown below.

$app->get('/home', function(Request $request, Response $response){
    $this->db->query("SET CHARACTER SET utf8");
    $sth = $this->db->prepare("My_Query");
    $sth->execute();
    $data = $sth->fetchAll();
    
    // Request with status response
    return $this->response->withJson($data, 200);
});

Step 5.  Now if you want to get form data and perform some action on database. You can create a function like bellow. You can access your database connection on $this->db variable after this your can create your query. If you want to pass data to query you can use bindParam(key, value)  to pass value in your query.

$app->post('/login', function(Request $request, Response $response){
    $data = $request->getParsedBody();
    // Check if we have user
    $auth = $this->db->prepare("select * from user where applicant_email= :email and password=:password");
    $auth->bindParam(':email', $data['email']);
    $auth->bindParam(':password', $data['password']);
    $auth->execute();
    if($auth->rowCount() > 0){
    	$responseData['status'] = 1;
    	$responseData['response'] = $auth->fetchAll();
    }else{
    	$responseData['status'] = 0;
    	$responseData['msg'] = 'Please enter valid login details.';
    }

    return $this->response->withJson($responseData, 200);
});

Remember you need to initialize your app at the end to do so you need to add below code at the end of script

$app->run();

This is a very basic example. This post guides you to setup and makes a basic request to the server using Slim framework.  If you want to learn more about Slim framework please post a comment.

Sample code for creating Application in Slim

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';

// Setting up database details
$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;

$config['db']['host']   = "";
$config['db']['user']   = "";
$config['db']['pass']   = "";
$config['db']['dbname'] = "";

$app = new \Slim\App(["settings" => $config]);

// Adding dependencies
$container = $app->getContainer();
$container['logger'] = function($c) {
    $logger = new \Monolog\Logger('my_logger');
    $file_handler = new \Monolog\Handler\StreamHandler("../logs/app.log");
    $logger->pushHandler($file_handler);
    return $logger;
};

// DB
$container['db'] = function ($c) {
    $db = $c['settings']['db'];
    $pdo = new PDO("mysql:host=" . $db['host'] . ";dbname=" . $db['dbname'],
        $db['user'], $db['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};

$app->get('/home', function(Request $request, Response $response){
    $this->db->query("SET CHARACTER SET utf8");
    $sth = $this->db->prepare("SHOW TABLES");
    $sth->execute();
    $data = $sth->fetchAll();
    
    return $this->response->withJson($data, 200);
});


$app->run();

 

Also, read Secure your Slim web services using JWT Auth.

If you like my blog please like and share my facebook page and share my blog thanks.