SlideShare a Scribd company logo
1 of 62
Creating REST Applications
with the Slim Micro-Framework




                                Vikram Vaswani
                                  October 2012
slim
adj. slim·mer, slim·mest
   1. Small in girth or thickness in proportion
      to height or length; slender.
   2. Small in quantity or amount; meager:
      slim chances of success.

            From www.thefreedictionary.com
slim
PHP micro framework that helps you
quickly write simple yet powerful web
applications and APIs.

           From www.slimframework.com
Micro-Frameworks in 20 18 Words
●   Lightweight
●   Short learning curve
●   Flexible
●   Single-purpose
●   Good for
    ●   Small, static websites
    ●   API development and testing
    ●   Rapid prototyping
PHP Micro-Frameworks
●   Silex                ●   Phraw
●   Limonade             ●   Photon
●   GluePHP              ●   Fitzgerald
●   FlightPHP            ●   phpMF
●   Fat-Free Framework   ●   Swiftlet
●   MicroMVC             ●   Tachyon
●   Bullet               ●   Pupcake
●   Bento                ●   Relax
●   Yolo                 ●   Lime
●   Fluphy               ●   Shield
●   Tonic                ●   Hydra
●   Phlyty               ●   Gum
Entrée
Introducing Slim

   "Slim is a PHP micro framework that helps you
 quickly write simple yet powerful web applications
                     and APIs."

          From www.slimframework.com
Key Features
●   Powerful router
    ●   Standard and custom HTTP methods
    ●   Route parameters with wildcards and conditions
    ●   Route middleware
●   Template rendering with custom views
●   Flash messages
●   Secure cookies with AES-256 encryption
Key Features
●   HTTP caching
●   Logging with custom log writers
●   Error handling and debugging
●   Middleware architecture
●   Simple configuration
●   Extensive documentation
●   Active, enthusiastic community
●   Licensed under the MIT Public License
First Taste
<?php
// load
require 'Slim/Slim.php';
SlimSlim::registerAutoloader();

// initialize
$app = new SlimSlim();

// map routes
$app->get('/eat/:food', function ($food) {
  echo "Yum! That $food looks fantastic!";
});

// ...and we're off!
$app->run();
First Taste
Main Course
Slim + REST
●   Define URI routes, parameters and HTTP methods
    ●   GET / POST / PUT / DELETE
    ●   /my/api/endpoint/:parameter
●   Map routes to callbacks
    ●   Accept and validate input parameters from request object
    ●   Perform custom processing within callback
    ●   Produce and return response object
Example: REST Resources




                                                  So urce : W ikipe dia
                          e n. wikipe dia. o rg /wiki/Pe rio dic_ table
REST API
GET /api/v1/elements        Retrieve all elements from the periodic table


GET /api/v1/elements/1      Retrieve element #1 (hydrogen)


POST /api/v1/elements       Create new element


PUT /api/v1/elements/28     Update element #28 (nickel)


DELETE /api/v1/elements/8   Delete element #8 (oxygen)
Resource Representation (MySQL)
CREATE TABLE IF NOT EXISTS `elements` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `num` int(11) NOT NULL,
 `name` varchar(255) NOT NULL,
 `symbol` char(2) NOT NULL,
 `weight` float NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB;


INSERT INTO `elements` (`id`, `num`, `name`, `symbol`,
`weight`) VALUES(1, 1, 'Hydrogen', 'H', 1.008);
INSERT INTO `elements` (`id`, `num`, `name`, `symbol`,
`weight`) VALUES(2, 2, 'Helium', 'He', 4.0026);
Resource Representation (JSON)
 {
 "id":"1",
 "num":"1",
 "name":"Hydrogen",
 "symbol":"H",
 "weight":"1.008"
 },{
 "id":"2",
 "num":"2",
 "name":"Helium",
 "symbol":"He",
 "weight":"4.0026"
 }
RedBeanPHP
<?php
// load
require 'RedBean/rb.php';


// set up database connection
R::setup('mysql:host=localhost;dbname=appdata','user','
pass');
R::freeze(true);


// get all records
$elements = R::find('elements');
RedBeanPHP
<?php
// get a single record
$element = R::findOne('elements', 'id=?',
array($id));


// update element record
$element->name = 'foo'


// save modified record
R::store($element);
REST API Implementation
<?php
$app->get('/api/v1/elements', function () { ... }

$app->get('/api/v1/elements/:id', function ($id) { ... }

$app->post('/api/v1/elements', function ($id) { ... }

$app->put('/api/v1/elements/:id', function ($id) { ... }

$app->delete('/api/v1/elements/:id', function ($id) { ... }
GET Request Handler
<?php
// handle GET requests for /api/v1/elements
$app->get('/api/v1/elements', function () use ($app) {
      // get all elements
      $elements = R::find('elements');


      // create JSON response
    $app->response()->header('Content-Type',
'application/json');
      echo json_encode(R::exportAll($elements));
});
GET Response
GET Request Handler
<?php
// handle GET requests for /api/v1/elements/*
$app->get('/api/v1/elements/:id', function ($id) use ($app) {
      // get element by id
      $article = R::findOne('elements', 'id=?', array($id));


      // create JSON response if element found
      // else send 404 server error
      if ($article) {
          $app->response()->header('Content-Type', 'application/json');
          echo json_encode(R::exportAll($article));
      } else {
          $app->response()->status(404);
      }
});
GET Response
In The News Recently...




                                                                                             So urce : Live Scie nce
                 www. live scie nce . co m/20 6 9 8 -e le me nts-pe rio dic-table -fle ro vium-live rmo rium. html
POST Request Handler
<?php
// handle POST requests for /api/v1/elements/*
$app->post('/api/v1/elements', function () use ($app) {
      // get request body, decode into PHP object
      $request = $app->request();
      $body = $request->getBody();
      $input = json_decode($body);


      // create and save element record
      $element = R::dispense('elements');
      $element->num = (string)$input->num;   // do same for other attributes
      R::store($element);


      // create and send JSON response
      $app->response()->status(201);
      $app->response()->header('Content-Type', 'application/json');
      echo json_encode(R::exportAll($element));
});
POST Request
POST Response
PUT Request Handler
<?php
// handle PUT requests for /api/v1/elements/*
$app->put('/api/v1/elements/:id', function ($id) use ($app) {
      // get request body, decode into PHP object
      $request = $app->request();
      $body = $request->getBody();
      $input = json_decode($body);


      // retrieve specified element record
      // save modified record, create and send JSON response
      $element = R::findOne('elements', 'id=?', array($id));
      if ($element) {
          $element->num = (string)$input->num;   // do same for other attributes
          R::store($element);
          $app->response()->header('Content-Type', 'application/json');
          echo json_encode(R::exportAll($element));
      } else {
          $app->response()->status(404);
      }
});
PUT Request
PUT Response
DELETE Request Handler
<?php
// handle DELETE requests for /api/v1/elements
$app->delete('/api/v1/elements/:id', function ($id) use ($app) {
      $request = $app->request();
      $element = R::findOne('elements', 'id=?', array($id));
      if ($element) {
          R::trash($element);
          $app->response()->status(204);
      } else {
          $app->response()->status(404);
      }
});
DELETE Response
Accompaniments
Common Requirements
●   Authentication
●   Parameter validation
●   Request logging
●   Multi-format support
Common Requirements
●   Authentication
●   Parameter validation
●   Request logging
●   Multi-format support
Middleware


"The purpose of middleware is to inspect, analyze, or
  modify the application environment, request, and
 response before and/or after the Slim application is
                     invoked."

           From docs.slimframework.com
Middleware Use Cases
●   Authentication/authorization
●   Request pre-processing
●   Response post-processing
●   Filter chaining
●   Logging
Example: API Authentication
<?php
// route middleware for simple API authentication
function authenticate(SlimRoute $route) {
      $app = SlimSlim::getInstance();
      $uid = $app->getEncryptedCookie('uid');
      $key = $app->getEncryptedCookie('key');
      if (validateUserKey($uid, $key) === false) {
          $app->halt(401);
      }
}


// add API authentication for GET requests
$app->get('/api/v1/elements', 'authenticate', function () use ($app) {
    // GET handler code here
});
Response to Unauthenticated API
Request
Common Requirements
●   Authentication
●   Parameter validation
●   Request logging
●   Multi-format support
Example: API Parameter Validation
●   Optional and mandatory route parameters:
<?php
$app->get('/api/v1/elements(/:symbol)', function
() use ($app) { ... };

●   Route conditions:
<?php
$app->get('/api/v1/elements/:id', function () use
($app) { ... }->conditions(array('id' => '[0-9]
{1,}'));
Common Requirements
●   Authentication
●   Parameter validation
●   Request logging
●   Multi-format support
Request Object
<?php
// get request object
$request = $app->request();


// get request headers as associative array
$headers = $request->headers();


// get request path
$type = $request->getPathInfo()


// get request IP address and host
$body = $request->getIp() . ',' . $request->getHost();
Example: API Request Logging
<?php
// initialize logger
$app = new SlimSlim(array(
    'log.enabled' => 'true',
    'log.writer' => new FileLogWriter()
));


class FileLogWriter {
    public function write($message) {
    file_put_contents('my.log', $message . PHP_EOL,
FILE_APPEND);
    }
}
Example: Request Logging
<?php
// handle GET requests for /api/v1/elements
$app->get('/api/v1/elements', function () use ($app) {
    // get request headers and log message
    $request = $app->request();
    $message = sprintf("%s [%s] "%s %s"",
        $request->getIp(),
        time(),
        $request->getMethod(),
        $request->getPathInfo()
    );
    $app->getLog()->info($message);


    // handler code
}
Common Requirements
●   Authentication
●   Parameter validation
●   Request logging
●   Multi-format support
Request Object
<?php
// get request object
$request = $app->request();


// get request parameters as associative array
$headers = $request->params();


// get cookies
$headers = $request->cookies();


// get request content type
$type = $request->getMediaType()


// get raw request body
$body = $request->getBody();
Example: API Multi-Format Support
<?php
$app->get('/api/v1/elements', function () use ($app) {
      // check request content type, send XML or JSON response
      $mediaType = $app->request()->getMediaType();
      if ($mediaType == 'application/xml') {
          $app->response()->header('Content-Type', 'application/xml');
          $xml = new SimpleXMLElement('<root/>');
          foreach (R::exportAll($elements) as $r) {
              $item = $xml->addChild('item');
              $item->addChild('id', $r['id']);   // do same for other attributes
          }
          echo $xml->asXml();
      } else if (($mediaType == 'application/json')) {
          $app->response()->header('Content-Type', 'application/json');
          echo json_encode(R::exportAll($elements));
      }
});
GET Response (XML)
POST Request (XML)
POST Response (XML)
Dessert
Performance




              Put simply:
                F = ma
Or, To Put It Another Way...



 “ If everything seems under control, you're not going
                     fast enough.”

                   - Mario Andretti



                                                                              So urce : Go o dre ads. co m
                           http: //www. g o o dre ads. co m/autho r/quo te s/21 1 56 9 4. M _ A tti
                                                                                           ario ndre
Weight
Framework             Self time (Milliseconds) Sum of calls
Slim 2.0.0            1,008                     3,612
Zend Framework 1.11   2,917                     4,616
Agavi 1.0.1           13,885                    25,988




   30000

   25000

   20000
                                                              Slim
   15000                                                      Zend Framework
                                                              Agavi
   10000

   5000

      0
                                 Sum of Calls
Requests Per Second
Framework             Throughput (Requests/
                                          Second)
Slim 2.0.0            29.43
Zend Framework 1.11   15.10
Agavi 1.0.1           2.44




   35

   30

   25

   20                                               Slim
                                                    Zend Framework
   15
                                                    Agavi
   10

   5

   0
                      Throughput
Minimum Request Time
Framework                          M R
                                    in. equest Time (Milliseconds)
Slim 2.0.0                         53
Zend Framework 1.11                123
Agavi 1.0.1                        412




   450
   400
   350
   300
   250                                                               Slim
                                                                     Zend Framework
   200
                                                                     Agavi
   150
   100
   50
    0
                      Min. Request Time
"Lies, Damned Lies and Statistics"
Test data based on informal testing
●   Apache JMeter
    ●   300 concurrent requests, averaged over 3 test runs
●   Dual-core Dell server @ 2.4 GhZ
●   Apache 2.2, PHP 5.3, Xdebug 2.2 and MySQL 5.1
●   Unoptimized applications; default framework
    settings
●   Your mileage may (and probably will) vary!
Resources
●   Usage docs: docs.slimframework.com
●   API docs: dev.slimframework.com/phpdocs
●   Source code: github.com/codeguy/Slim
●   Forums: help.slimframework.com
●   News: www.slimframework.com/news
●   Twitter: @slimphp
Questions?
Contact Information
Email:
●   vikram-vaswani.in/contact
Web:
●   www.melonfire.com
●   vikram-vaswani.in
Social networks:
●   plus.google.com/100028886433648406825

More Related Content

What's hot

Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaEdureka!
 
영속성 컨텍스트로 보는 JPA
영속성 컨텍스트로 보는 JPA영속성 컨텍스트로 보는 JPA
영속성 컨텍스트로 보는 JPA경원 이
 
Node.js - #1 - Introdução - Rodrigo Branas
Node.js - #1 - Introdução - Rodrigo BranasNode.js - #1 - Introdução - Rodrigo Branas
Node.js - #1 - Introdução - Rodrigo BranasRodrigo Branas
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with geventMahendra M
 
Observability in Java: Getting Started with OpenTelemetry
Observability in Java: Getting Started with OpenTelemetryObservability in Java: Getting Started with OpenTelemetry
Observability in Java: Getting Started with OpenTelemetryDevOps.com
 
Async ... Await – concurrency in java script
Async ... Await – concurrency in java scriptAsync ... Await – concurrency in java script
Async ... Await – concurrency in java scriptAthman Gude
 
Observability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringObservability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringVMware Tanzu
 
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요Jo Hoon
 
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...Amazon Web Services Korea
 
Open source APM Scouter로 모니터링 잘 하기
Open source APM Scouter로 모니터링 잘 하기Open source APM Scouter로 모니터링 잘 하기
Open source APM Scouter로 모니터링 잘 하기GunHee Lee
 
[Webinar]: Working with Reactive Spring
[Webinar]: Working with Reactive Spring[Webinar]: Working with Reactive Spring
[Webinar]: Working with Reactive SpringKnoldus Inc.
 
Gitlab Training with GIT and SourceTree
Gitlab Training with GIT and SourceTreeGitlab Training with GIT and SourceTree
Gitlab Training with GIT and SourceTreeTeerapat Khunpech
 
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...Henning Jacobs
 
Useful Linux and Unix commands handbook
Useful Linux and Unix commands handbookUseful Linux and Unix commands handbook
Useful Linux and Unix commands handbookWave Digitech
 
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at RuntimeOSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at RuntimeNETWAYS
 
如何使用 Xhprof 分析網站效能 (真實案例2)
如何使用 Xhprof 分析網站效能 (真實案例2)如何使用 Xhprof 分析網站效能 (真實案例2)
如何使用 Xhprof 分析網站效能 (真實案例2)Cyril Wang
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101Itiel Shwartz
 

What's hot (20)

Shell Scripting Tutorial | Edureka
Shell Scripting Tutorial | EdurekaShell Scripting Tutorial | Edureka
Shell Scripting Tutorial | Edureka
 
영속성 컨텍스트로 보는 JPA
영속성 컨텍스트로 보는 JPA영속성 컨텍스트로 보는 JPA
영속성 컨텍스트로 보는 JPA
 
Node.js - #1 - Introdução - Rodrigo Branas
Node.js - #1 - Introdução - Rodrigo BranasNode.js - #1 - Introdução - Rodrigo Branas
Node.js - #1 - Introdução - Rodrigo Branas
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
 
Introduction à ajax
Introduction à ajaxIntroduction à ajax
Introduction à ajax
 
Observability in Java: Getting Started with OpenTelemetry
Observability in Java: Getting Started with OpenTelemetryObservability in Java: Getting Started with OpenTelemetry
Observability in Java: Getting Started with OpenTelemetry
 
Async ... Await – concurrency in java script
Async ... Await – concurrency in java scriptAsync ... Await – concurrency in java script
Async ... Await – concurrency in java script
 
Observability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with SpringObservability: Beyond the Three Pillars with Spring
Observability: Beyond the Three Pillars with Spring
 
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
 
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...
옵저버빌러티(Observability) 확보로 서버리스 마이크로서비스 들여다보기 - 김형일 AWS 솔루션즈 아키텍트 :: AWS Summi...
 
Open source APM Scouter로 모니터링 잘 하기
Open source APM Scouter로 모니터링 잘 하기Open source APM Scouter로 모니터링 잘 하기
Open source APM Scouter로 모니터링 잘 하기
 
[Webinar]: Working with Reactive Spring
[Webinar]: Working with Reactive Spring[Webinar]: Working with Reactive Spring
[Webinar]: Working with Reactive Spring
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Gitlab Training with GIT and SourceTree
Gitlab Training with GIT and SourceTreeGitlab Training with GIT and SourceTree
Gitlab Training with GIT and SourceTree
 
HTTP web server 구현
HTTP web server 구현HTTP web server 구현
HTTP web server 구현
 
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...
Optimizing Kubernetes Resource Requests/Limits for Cost-Efficiency and Latenc...
 
Useful Linux and Unix commands handbook
Useful Linux and Unix commands handbookUseful Linux and Unix commands handbook
Useful Linux and Unix commands handbook
 
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at RuntimeOSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
OSMC 2021 | inspectIT Ocelot: Dynamic OpenTelemetry Instrumentation at Runtime
 
如何使用 Xhprof 分析網站效能 (真實案例2)
如何使用 Xhprof 分析網站效能 (真實案例2)如何使用 Xhprof 分析網站效能 (真實案例2)
如何使用 Xhprof 分析網站效能 (真實案例2)
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101
 

Viewers also liked

Hello World on Slim Framework 3.x
Hello World on Slim Framework 3.xHello World on Slim Framework 3.x
Hello World on Slim Framework 3.xRyan Szrama
 
Micro Web Service - Slim and JWT
Micro Web Service - Slim and JWTMicro Web Service - Slim and JWT
Micro Web Service - Slim and JWTTuyen Vuong
 
Web 2.0 - From a Social to a Service Web
Web 2.0 - From a Social to a Service WebWeb 2.0 - From a Social to a Service Web
Web 2.0 - From a Social to a Service WebJury Konga
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkJeremy Kendall
 
Taking Care of The REST - Creating your own RESTful API Server using Restler 2.0
Taking Care of The REST - Creating your own RESTful API Server using Restler 2.0Taking Care of The REST - Creating your own RESTful API Server using Restler 2.0
Taking Care of The REST - Creating your own RESTful API Server using Restler 2.0Arul Kumaran
 
AtlasCamp2014: Introducing the Confluence REST API
AtlasCamp2014: Introducing the Confluence REST APIAtlasCamp2014: Introducing the Confluence REST API
AtlasCamp2014: Introducing the Confluence REST APIAtlassian
 
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)iMasters
 
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Arc & Codementor
 
Os mitos do desenvolvimento front-end
Os mitos do desenvolvimento front-endOs mitos do desenvolvimento front-end
Os mitos do desenvolvimento front-endZeno Rocha
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
What they don't tell you about sugarcrm community edition
What they don't tell you about sugarcrm community editionWhat they don't tell you about sugarcrm community edition
What they don't tell you about sugarcrm community editionsalesagility
 
Json web token api authorization
Json web token api authorizationJson web token api authorization
Json web token api authorizationGiulio De Donato
 
Servicio y Consumo de Servicios REST en PHP
Servicio y Consumo de Servicios REST en PHPServicio y Consumo de Servicios REST en PHP
Servicio y Consumo de Servicios REST en PHPDavid J. Brenes
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkJeremy Kendall
 
Api anti patterns
Api anti patternsApi anti patterns
Api anti patternsMike Pearce
 
Securing Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationSecuring Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationStormpath
 

Viewers also liked (20)

Hello World on Slim Framework 3.x
Hello World on Slim Framework 3.xHello World on Slim Framework 3.x
Hello World on Slim Framework 3.x
 
Micro Web Service - Slim and JWT
Micro Web Service - Slim and JWTMicro Web Service - Slim and JWT
Micro Web Service - Slim and JWT
 
Web 2.0 - From a Social to a Service Web
Web 2.0 - From a Social to a Service WebWeb 2.0 - From a Social to a Service Web
Web 2.0 - From a Social to a Service Web
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro Framework
 
Taking Care of The REST - Creating your own RESTful API Server using Restler 2.0
Taking Care of The REST - Creating your own RESTful API Server using Restler 2.0Taking Care of The REST - Creating your own RESTful API Server using Restler 2.0
Taking Care of The REST - Creating your own RESTful API Server using Restler 2.0
 
Slim Framework
Slim FrameworkSlim Framework
Slim Framework
 
AtlasCamp2014: Introducing the Confluence REST API
AtlasCamp2014: Introducing the Confluence REST APIAtlasCamp2014: Introducing the Confluence REST API
AtlasCamp2014: Introducing the Confluence REST API
 
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
 
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
 
Os mitos do desenvolvimento front-end
Os mitos do desenvolvimento front-endOs mitos do desenvolvimento front-end
Os mitos do desenvolvimento front-end
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
What they don't tell you about sugarcrm community edition
What they don't tell you about sugarcrm community editionWhat they don't tell you about sugarcrm community edition
What they don't tell you about sugarcrm community edition
 
Git and git flow
Git and git flowGit and git flow
Git and git flow
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
 
Json web token api authorization
Json web token api authorizationJson web token api authorization
Json web token api authorization
 
Servicio y Consumo de Servicios REST en PHP
Servicio y Consumo de Servicios REST en PHPServicio y Consumo de Servicios REST en PHP
Servicio y Consumo de Servicios REST en PHP
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro framework
 
Api anti patterns
Api anti patternsApi anti patterns
Api anti patterns
 
Securing Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationSecuring Web Applications with Token Authentication
Securing Web Applications with Token Authentication
 

Similar to Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani

REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterSachin G Kulkarni
 
Cakefest 2010: API Development
Cakefest 2010: API DevelopmentCakefest 2010: API Development
Cakefest 2010: API DevelopmentAndrew Curioso
 
api-platform: the ultimate API platform
api-platform: the ultimate API platformapi-platform: the ultimate API platform
api-platform: the ultimate API platformStefan Adolf
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryTatsuhiko Miyagawa
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmsom_nangia
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmwilburlo
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platformsAyush Sharma
 
Building WordPress Client Side Applications with WP and WP-API - #wcmia
Building WordPress Client Side Applications with WP and WP-API - #wcmiaBuilding WordPress Client Side Applications with WP and WP-API - #wcmia
Building WordPress Client Side Applications with WP and WP-API - #wcmiaRoy Sivan
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Nordic APIs
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013Kiril Iliev
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST APICaldera Labs
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207patter
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 

Similar to Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani (20)

REST API for your WP7 App
REST API for your WP7 AppREST API for your WP7 App
REST API for your WP7 App
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 
Cakefest 2010: API Development
Cakefest 2010: API DevelopmentCakefest 2010: API Development
Cakefest 2010: API Development
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
api-platform: the ultimate API platform
api-platform: the ultimate API platformapi-platform: the ultimate API platform
api-platform: the ultimate API platform
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Complex Sites with Silex
Complex Sites with SilexComplex Sites with Silex
Complex Sites with Silex
 
Flask and Angular: An approach to build robust platforms
Flask and Angular:  An approach to build robust platformsFlask and Angular:  An approach to build robust platforms
Flask and Angular: An approach to build robust platforms
 
Building WordPress Client Side Applications with WP and WP-API - #wcmia
Building WordPress Client Side Applications with WP and WP-API - #wcmiaBuilding WordPress Client Side Applications with WP and WP-API - #wcmia
Building WordPress Client Side Applications with WP and WP-API - #wcmia
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
 
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
jsSaturday - PhoneGap and jQuery Mobile for SharePoint 2013
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 

Recently uploaded

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani

  • 1. Creating REST Applications with the Slim Micro-Framework Vikram Vaswani October 2012
  • 2. slim adj. slim·mer, slim·mest 1. Small in girth or thickness in proportion to height or length; slender. 2. Small in quantity or amount; meager: slim chances of success. From www.thefreedictionary.com
  • 3. slim PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. From www.slimframework.com
  • 4. Micro-Frameworks in 20 18 Words ● Lightweight ● Short learning curve ● Flexible ● Single-purpose ● Good for ● Small, static websites ● API development and testing ● Rapid prototyping
  • 5. PHP Micro-Frameworks ● Silex ● Phraw ● Limonade ● Photon ● GluePHP ● Fitzgerald ● FlightPHP ● phpMF ● Fat-Free Framework ● Swiftlet ● MicroMVC ● Tachyon ● Bullet ● Pupcake ● Bento ● Relax ● Yolo ● Lime ● Fluphy ● Shield ● Tonic ● Hydra ● Phlyty ● Gum
  • 7. Introducing Slim "Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs." From www.slimframework.com
  • 8. Key Features ● Powerful router ● Standard and custom HTTP methods ● Route parameters with wildcards and conditions ● Route middleware ● Template rendering with custom views ● Flash messages ● Secure cookies with AES-256 encryption
  • 9. Key Features ● HTTP caching ● Logging with custom log writers ● Error handling and debugging ● Middleware architecture ● Simple configuration ● Extensive documentation ● Active, enthusiastic community ● Licensed under the MIT Public License
  • 10. First Taste <?php // load require 'Slim/Slim.php'; SlimSlim::registerAutoloader(); // initialize $app = new SlimSlim(); // map routes $app->get('/eat/:food', function ($food) { echo "Yum! That $food looks fantastic!"; }); // ...and we're off! $app->run();
  • 13. Slim + REST ● Define URI routes, parameters and HTTP methods ● GET / POST / PUT / DELETE ● /my/api/endpoint/:parameter ● Map routes to callbacks ● Accept and validate input parameters from request object ● Perform custom processing within callback ● Produce and return response object
  • 14. Example: REST Resources So urce : W ikipe dia e n. wikipe dia. o rg /wiki/Pe rio dic_ table
  • 15. REST API GET /api/v1/elements Retrieve all elements from the periodic table GET /api/v1/elements/1 Retrieve element #1 (hydrogen) POST /api/v1/elements Create new element PUT /api/v1/elements/28 Update element #28 (nickel) DELETE /api/v1/elements/8 Delete element #8 (oxygen)
  • 16. Resource Representation (MySQL) CREATE TABLE IF NOT EXISTS `elements` ( `id` int(11) NOT NULL AUTO_INCREMENT, `num` int(11) NOT NULL, `name` varchar(255) NOT NULL, `symbol` char(2) NOT NULL, `weight` float NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; INSERT INTO `elements` (`id`, `num`, `name`, `symbol`, `weight`) VALUES(1, 1, 'Hydrogen', 'H', 1.008); INSERT INTO `elements` (`id`, `num`, `name`, `symbol`, `weight`) VALUES(2, 2, 'Helium', 'He', 4.0026);
  • 17. Resource Representation (JSON) { "id":"1", "num":"1", "name":"Hydrogen", "symbol":"H", "weight":"1.008" },{ "id":"2", "num":"2", "name":"Helium", "symbol":"He", "weight":"4.0026" }
  • 18. RedBeanPHP <?php // load require 'RedBean/rb.php'; // set up database connection R::setup('mysql:host=localhost;dbname=appdata','user',' pass'); R::freeze(true); // get all records $elements = R::find('elements');
  • 19. RedBeanPHP <?php // get a single record $element = R::findOne('elements', 'id=?', array($id)); // update element record $element->name = 'foo' // save modified record R::store($element);
  • 20. REST API Implementation <?php $app->get('/api/v1/elements', function () { ... } $app->get('/api/v1/elements/:id', function ($id) { ... } $app->post('/api/v1/elements', function ($id) { ... } $app->put('/api/v1/elements/:id', function ($id) { ... } $app->delete('/api/v1/elements/:id', function ($id) { ... }
  • 21. GET Request Handler <?php // handle GET requests for /api/v1/elements $app->get('/api/v1/elements', function () use ($app) { // get all elements $elements = R::find('elements'); // create JSON response $app->response()->header('Content-Type', 'application/json'); echo json_encode(R::exportAll($elements)); });
  • 23. GET Request Handler <?php // handle GET requests for /api/v1/elements/* $app->get('/api/v1/elements/:id', function ($id) use ($app) { // get element by id $article = R::findOne('elements', 'id=?', array($id)); // create JSON response if element found // else send 404 server error if ($article) { $app->response()->header('Content-Type', 'application/json'); echo json_encode(R::exportAll($article)); } else { $app->response()->status(404); } });
  • 25. In The News Recently... So urce : Live Scie nce www. live scie nce . co m/20 6 9 8 -e le me nts-pe rio dic-table -fle ro vium-live rmo rium. html
  • 26. POST Request Handler <?php // handle POST requests for /api/v1/elements/* $app->post('/api/v1/elements', function () use ($app) { // get request body, decode into PHP object $request = $app->request(); $body = $request->getBody(); $input = json_decode($body); // create and save element record $element = R::dispense('elements'); $element->num = (string)$input->num; // do same for other attributes R::store($element); // create and send JSON response $app->response()->status(201); $app->response()->header('Content-Type', 'application/json'); echo json_encode(R::exportAll($element)); });
  • 29. PUT Request Handler <?php // handle PUT requests for /api/v1/elements/* $app->put('/api/v1/elements/:id', function ($id) use ($app) { // get request body, decode into PHP object $request = $app->request(); $body = $request->getBody(); $input = json_decode($body); // retrieve specified element record // save modified record, create and send JSON response $element = R::findOne('elements', 'id=?', array($id)); if ($element) { $element->num = (string)$input->num; // do same for other attributes R::store($element); $app->response()->header('Content-Type', 'application/json'); echo json_encode(R::exportAll($element)); } else { $app->response()->status(404); } });
  • 32. DELETE Request Handler <?php // handle DELETE requests for /api/v1/elements $app->delete('/api/v1/elements/:id', function ($id) use ($app) { $request = $app->request(); $element = R::findOne('elements', 'id=?', array($id)); if ($element) { R::trash($element); $app->response()->status(204); } else { $app->response()->status(404); } });
  • 35. Common Requirements ● Authentication ● Parameter validation ● Request logging ● Multi-format support
  • 36. Common Requirements ● Authentication ● Parameter validation ● Request logging ● Multi-format support
  • 37. Middleware "The purpose of middleware is to inspect, analyze, or modify the application environment, request, and response before and/or after the Slim application is invoked." From docs.slimframework.com
  • 38. Middleware Use Cases ● Authentication/authorization ● Request pre-processing ● Response post-processing ● Filter chaining ● Logging
  • 39. Example: API Authentication <?php // route middleware for simple API authentication function authenticate(SlimRoute $route) { $app = SlimSlim::getInstance(); $uid = $app->getEncryptedCookie('uid'); $key = $app->getEncryptedCookie('key'); if (validateUserKey($uid, $key) === false) { $app->halt(401); } } // add API authentication for GET requests $app->get('/api/v1/elements', 'authenticate', function () use ($app) { // GET handler code here });
  • 41. Common Requirements ● Authentication ● Parameter validation ● Request logging ● Multi-format support
  • 42. Example: API Parameter Validation ● Optional and mandatory route parameters: <?php $app->get('/api/v1/elements(/:symbol)', function () use ($app) { ... }; ● Route conditions: <?php $app->get('/api/v1/elements/:id', function () use ($app) { ... }->conditions(array('id' => '[0-9] {1,}'));
  • 43. Common Requirements ● Authentication ● Parameter validation ● Request logging ● Multi-format support
  • 44. Request Object <?php // get request object $request = $app->request(); // get request headers as associative array $headers = $request->headers(); // get request path $type = $request->getPathInfo() // get request IP address and host $body = $request->getIp() . ',' . $request->getHost();
  • 45. Example: API Request Logging <?php // initialize logger $app = new SlimSlim(array( 'log.enabled' => 'true', 'log.writer' => new FileLogWriter() )); class FileLogWriter { public function write($message) { file_put_contents('my.log', $message . PHP_EOL, FILE_APPEND); } }
  • 46. Example: Request Logging <?php // handle GET requests for /api/v1/elements $app->get('/api/v1/elements', function () use ($app) { // get request headers and log message $request = $app->request(); $message = sprintf("%s [%s] "%s %s"", $request->getIp(), time(), $request->getMethod(), $request->getPathInfo() ); $app->getLog()->info($message); // handler code }
  • 47. Common Requirements ● Authentication ● Parameter validation ● Request logging ● Multi-format support
  • 48. Request Object <?php // get request object $request = $app->request(); // get request parameters as associative array $headers = $request->params(); // get cookies $headers = $request->cookies(); // get request content type $type = $request->getMediaType() // get raw request body $body = $request->getBody();
  • 49. Example: API Multi-Format Support <?php $app->get('/api/v1/elements', function () use ($app) { // check request content type, send XML or JSON response $mediaType = $app->request()->getMediaType(); if ($mediaType == 'application/xml') { $app->response()->header('Content-Type', 'application/xml'); $xml = new SimpleXMLElement('<root/>'); foreach (R::exportAll($elements) as $r) { $item = $xml->addChild('item'); $item->addChild('id', $r['id']); // do same for other attributes } echo $xml->asXml(); } else if (($mediaType == 'application/json')) { $app->response()->header('Content-Type', 'application/json'); echo json_encode(R::exportAll($elements)); } });
  • 54. Performance Put simply: F = ma
  • 55. Or, To Put It Another Way... “ If everything seems under control, you're not going fast enough.” - Mario Andretti So urce : Go o dre ads. co m http: //www. g o o dre ads. co m/autho r/quo te s/21 1 56 9 4. M _ A tti ario ndre
  • 56. Weight Framework Self time (Milliseconds) Sum of calls Slim 2.0.0 1,008 3,612 Zend Framework 1.11 2,917 4,616 Agavi 1.0.1 13,885 25,988 30000 25000 20000 Slim 15000 Zend Framework Agavi 10000 5000 0 Sum of Calls
  • 57. Requests Per Second Framework Throughput (Requests/ Second) Slim 2.0.0 29.43 Zend Framework 1.11 15.10 Agavi 1.0.1 2.44 35 30 25 20 Slim Zend Framework 15 Agavi 10 5 0 Throughput
  • 58. Minimum Request Time Framework M R in. equest Time (Milliseconds) Slim 2.0.0 53 Zend Framework 1.11 123 Agavi 1.0.1 412 450 400 350 300 250 Slim Zend Framework 200 Agavi 150 100 50 0 Min. Request Time
  • 59. "Lies, Damned Lies and Statistics" Test data based on informal testing ● Apache JMeter ● 300 concurrent requests, averaged over 3 test runs ● Dual-core Dell server @ 2.4 GhZ ● Apache 2.2, PHP 5.3, Xdebug 2.2 and MySQL 5.1 ● Unoptimized applications; default framework settings ● Your mileage may (and probably will) vary!
  • 60. Resources ● Usage docs: docs.slimframework.com ● API docs: dev.slimframework.com/phpdocs ● Source code: github.com/codeguy/Slim ● Forums: help.slimframework.com ● News: www.slimframework.com/news ● Twitter: @slimphp
  • 62. Contact Information Email: ● vikram-vaswani.in/contact Web: ● www.melonfire.com ● vikram-vaswani.in Social networks: ● plus.google.com/100028886433648406825

Editor's Notes

  1. Typically less than 200-300 KB in size. Slim is ~200 KB. Based on ideas promulgated by Sinatra (Ruby). Reduces overall size of project. Most projects use 5% of a full-stack framework like Zend, Symfony, etc.
  2. The modified object is then saved back to the database, and a JSON representation returned to the caller with a 200 server response code. In the event that the identifier provided does not match an existing resource, a custom exception is thrown and a 404 server error response sent back to the client.
  3. The response to a successful DELETE request can be a 200 (OK) with the status in the response body, or a 204 (No Content) with an empty response body