SlideShare a Scribd company logo
Silex: From nothing, to an API




Sunday, 21 April 13
About me


                                  I'm Chris Kemper

             I work at Drummond Central, but I also freelance

                      I've been in the industry for around 5 years

       I've written a book with a snake on the cover (It's on
                 Version Control, if you didn't know)

                               I also own an elePHPant


Sunday, 21 April 13
About me

                                 Pies




                          Cows

Sunday, 21 April 13
What is Silex?




                       "Silex is a PHP microframework for PHP 5.3. It is built on the
                      shoulders of Symfony2 and Pimple and also inspired by sinatra."


                              Created by Fabien Potencier and Igor Wiedler




Sunday, 21 April 13
Getting started

                           You can download it from the site directly
                                   http://silex.sensiolabs.org/


                         Or, you can get with the times and use Composer




                                   {
                                     "require": {
                                       "silex/silex": "1.0.*@dev"
                                   ! }
                                   }




Sunday, 21 April 13
Your first end point

                      I’ve used Composer, so after it’s all installed, you can add the first end
                                                       point!




         require_once __DIR__.'/../vendor/autoload.php';

         $app = new SilexApplication();

         $app->get('/hello/{name}', function($name) use($app) {
             !return 'Hello '.$app->escape($name);
         });

         $app->run();




Sunday, 21 April 13
Don’t forget about .htaccess

                      Composer doesn’t pull it down, do don’t forget to put it in.


         <IfModule mod_rewrite.c>
             Options -MultiViews

             RewriteEngine On
             #RewriteBase /path/to/app
             RewriteCond %{REQUEST_FILENAME} !-f
             RewriteRule ^ index.php [L]
         </IfModule>


                           If you’re using Apache 2.2.16+, then you can use:




         FallbackResource /index.php




Sunday, 21 April 13
nginx works too!

         server {
             location = / {
                  try_files @site @site;
             }

                      location / {
                          try_files $uri $uri/ @site;
                      }

                      location ~ .php$ {
                          return 404;
                      }

                      location @site {
                          fastcgi_pass   unix:/var/run/php-fpm/www.sock;
                          include fastcgi_params;
                          fastcgi_param SCRIPT_FILENAME $document_root/index.php;
                          #fastcgi_param HTTPS on;
                      }
         }

Sunday, 21 April 13
Using a templating language

                      You don’t always want to output strings, so let’s use Twig, because it’s
                                                  awesome.




                                        {
                                            "require": {
                                              "silex/silex": "1.0.*@dev",
                                              "twig/twig": ">=1.8,<2.0-dev",
                                              "symfony/twig-bridge": "~2.1"
                                            }
                                        }




Sunday, 21 April 13
Register the Twig Service provider

         $app->register(new SilexProviderTwigServiceProvider(), array(
         !    'twig.path' => __DIR__.'/views',
         ));



                                   Now to use it




         $app->get('/hello/{name}', function ($name) use ($app) {
             !return $app['twig']->render('hello.twig', array(
             !    'name' => $name,
              ));
         });




Sunday, 21 April 13
So many more Service providers




                             Check the docs at http://silex.sensiolabs.org/documentation

                 There are a boat load of Built-in Service Providers which you can take advantage of!

                       Doctrine, Monolog, Form and Validation are just a couple of examples.




Sunday, 21 April 13
Tips: Extending the base application

  This allows you to add, anything to the base application to
                  make your own life easier.

                                 First of all, you need a class


         <?php
         namespace Acme;

         use
                      SilexApplication as BaseApplication;

         class Application extends BaseApplication {

         }


Sunday, 21 April 13
Tips: Extending the base application

                      Now time to autoload that class, psr-0 style.


                                  {
                                      "require": {
                                          "silex/silex": "1.0.*@dev",
                                          "twig/twig": ">=1.8,<2.0-dev",
                                          "symfony/twig-bridge": "~2.1"!
                                      },
                                      "autoload": {
                                          "psr-0": {"Acme": "src/"}
                                      }
                                  }




Sunday, 21 April 13
Tips: Separate your config and routes

   app/bootstrap.php
                      require_once __DIR__ . '/../vendor/autoload.php';

                      use
                      !   SymfonyComponentHttpFoundationRequest,
                      !   SymfonyComponentHttpFoundationResponse;

                      use
                      !   AcmeApplication;

                      $app = new Application;

                      $app->register(new SilexProviderTwigServiceProvider(),
                      array(
                      !   'twig.path' => __DIR__.'/views',
                      ));

                      return $app;


Sunday, 21 April 13
Tips: Separate your config and routes

   web/index.php




                      <?php

                      $app = include __DIR__ . '/../app/bootstrap.php';

                      $app->get('/hello/{name}', function ($name) use ($app) {
                          return $app['twig']->render('hello.twig', array(
                              'name' => $name,
                          ));
                      });

                      $app->run();




Sunday, 21 April 13
Let's make an API



        Silex is great for API's, so let's make one. Here is the groundwork for a basic
                                           user-based API

     Some lovely endpoints:

     Create a user (/user) - This will use POST to create a new user in the DB.
     Update a user (/user/{id}) - This will use PUT to update the user
     View a user (/user/{id}) - This will use GET to view the users information
     Delete a user (/user/{id}) - Yes you guessed it, this uses the DELETE method.




Sunday, 21 April 13
More dependencies!

              If we want to use a database, we'll need to define one. Let's get DBAL!



                                   {
                                       "require": {
                                           "silex/silex": "1.0.*@dev",
                                           "twig/twig": ">=1.8,<2.0-dev",
                                           "symfony/twig-bridge": "~2.1",
                                           "doctrine/dbal": "2.2.*"
                                       },
                                       "autoload": {
                                           "psr-0": {"Acme": "src/"}
                                       }
                                   }




Sunday, 21 April 13
More dependencies!

                       It'll just be MySQL so let's configure that




         $app->register(new DoctrineServiceProvider(), array(
         !    'db.options' => array(
         !    ! 'dbname' ! => 'acme',
         !    ! 'user' ! ! => 'root',
         !    ! 'password' ! => 'root',
         !    ! 'host' ! ! => 'localhost',
         !    ! 'driver' ! => 'pdo_mysql',
         !    ),
         ));




Sunday, 21 April 13
Show me your endpoints: POST

                      Before we can do anything, we need to create some users.



         $app->post('/user', function (Request $request) use ($app) {
           $user = array(
               'email' => $request->get('email'),
         !     'name' => $request->get('name')
           );

              $app['db']->insert('user', $user);

           return new Response("User " . $app['db']->lastInsertId() . "
           created", 201);
         });




Sunday, 21 April 13
Show me your endpoints: PUT

                          To update the users, we need to use PUT



         $app->put('/user/{id}', function (Request $request, $id) use
         ($app) {
           $sql = "UPDATE user SET email = ?, name = ? WHERE id = ?";

              $app['db']->executeUpdate($sql, array(
                $request->get('email'),
                $request->get('name'),
                 (int) $id)
              );
         !
           return new Response("User " . $id . " updated", 303);
         });




Sunday, 21 April 13
Show me your endpoints: GET

                            Let's get the API to output the user data as JSON




         $app->get('/user/{id}', function (Request $request, $id) use
         ($app) {
             $sql = "SELECT * FROM user WHERE id = ?";
             $post = $app['db']->fetchAssoc($sql, array((int) $id));

                      return $app->json($post, 201);
         });




Sunday, 21 April 13
Show me your endpoints: DELETE

                                       Lastly, we have DELETE




         $app->delete('/user/{id}', function (Request $request, $id) use
         ($app) {
             $sql = "DELETE FROM user WHERE id = ?";
             $app['db']->executeUpdate($sql, array((int) $id));

                      return new Response("User " . $id . " deleted", 303);
         });




Sunday, 21 April 13
A note about match()

                      Using match, you can catch any method used on a route. Like so:

         $app->match('/user', function () use ($app) {
         !    ...
         });



             You can also limit the method accepted by match by using the 'method'
                                            method

         $app->match('/user', function () use ($app) {
         !    ...
         })->method('PUT|POST');




Sunday, 21 April 13
Using before() and after()

        Each request, can be pre, or post processed. In this case, it could be used for
                                            auth.


         $before = function (Request $request) use ($app) {
             ...
         };

         $after = function (Request $request) use ($app) {
             ...
         };

         $app->match('/user', function () use ($app) {
             ...
         })
         ->before($before)
         ->after($after);




Sunday, 21 April 13
Using before() and after()

                            This can also be used globally, like so:

         $app->before(function(Request $request) use ($app) {
             ...
         });



         You can also make an event be as early as possible, or as late as possible by
           using Application::EARLY_EVENT and Application::LATE_EVENT, respectively.


         $app->before(function(Request $request) use ($app) {
             ...
         }, Application::EARLY_EVENT);




Sunday, 21 April 13
Time for a demo




Sunday, 21 April 13
Summary


              This is just a small amount of what Silex is capable
                                   of, try it out.

                                  Thank You!

                          http://silex.sensiolabs.org/
                               @chrisdkemper
                          http://chrisdkemper.co.uk




Sunday, 21 April 13

More Related Content

What's hot

What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
Jace Ju
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
Antonio Peric-Mazar
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and Knockout
Vic Metcalfe
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationJace Ju
 
Zend framework
Zend frameworkZend framework
Zend framework
Prem Shankar
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
Paul Bearne
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
Abdul Malik Ikhsan
 
The Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/PressThe Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/Press
Jeroen van Dijk
 
Symfony2 and AngularJS
Symfony2 and AngularJSSymfony2 and AngularJS
Symfony2 and AngularJS
Antonio Peric-Mazar
 
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreSymfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Ryan Weaver
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVCJace Ju
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
Jeroen van Dijk
 
New in php 7
New in php 7New in php 7
New in php 7
Vic Metcalfe
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
The Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/PressThe Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/Press
Jeroen van Dijk
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
Jeroen van Dijk
 
21.search in laravel
21.search in laravel21.search in laravel
21.search in laravel
Razvan Raducanu, PhD
 
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Cirdes Filho
 

What's hot (20)

What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
 
Phinx talk
Phinx talkPhinx talk
Phinx talk
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and Knockout
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & Application
 
Zend framework
Zend frameworkZend framework
Zend framework
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
The Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/PressThe Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/Press
 
Symfony2 and AngularJS
Symfony2 and AngularJSSymfony2 and AngularJS
Symfony2 and AngularJS
 
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and moreSymfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
 
深入淺出 MVC
深入淺出 MVC深入淺出 MVC
深入淺出 MVC
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
New in php 7
New in php 7New in php 7
New in php 7
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
The Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/PressThe Enterprise Wor/d/thy/Press
The Enterprise Wor/d/thy/Press
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
21.search in laravel
21.search in laravel21.search in laravel
21.search in laravel
 
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
 

Viewers also liked

Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
Hugo Hamon
 
Introducción a Silex. Aprendiendo a hacer las cosas bien en PHP
Introducción a Silex. Aprendiendo a hacer las cosas bien en PHPIntroducción a Silex. Aprendiendo a hacer las cosas bien en PHP
Introducción a Silex. Aprendiendo a hacer las cosas bien en PHP
Daniel Primo
 
Silex 入門
Silex 入門Silex 入門
Silex 入門
Masao Maeda
 
Silex入門
Silex入門Silex入門
Silex入門
Takuya Sato
 
Your marketing funnel is a hot mess
Your marketing funnel is a hot messYour marketing funnel is a hot mess
Your marketing funnel is a hot mess
GetResponse
 
Silex, the microframework
Silex, the microframeworkSilex, the microframework
Silex, the microframework
Inviqa
 
Google drive for nonprofits webinar
Google drive for nonprofits webinarGoogle drive for nonprofits webinar
Google drive for nonprofits webinarCraig Grella
 
&lt;iframe src="//www.slideshare.net/slideshow/embed_code/42392945" width="47...
&lt;iframe src="//www.slideshare.net/slideshow/embed_code/42392945" width="47...&lt;iframe src="//www.slideshare.net/slideshow/embed_code/42392945" width="47...
&lt;iframe src="//www.slideshare.net/slideshow/embed_code/42392945" width="47...
Reputation VIP
 
Project performance tracking analysis and reporting
Project performance tracking analysis and reportingProject performance tracking analysis and reporting
Project performance tracking analysis and reporting
Charles Cotter, PhD
 
How to Embed a PowerPoint Presentation Using SlideShare
How to Embed a PowerPoint Presentation Using SlideShareHow to Embed a PowerPoint Presentation Using SlideShare
How to Embed a PowerPoint Presentation Using SlideShareJoie Ocon
 
Optimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing FunnelOptimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing Funnel
HubSpot
 
Windows 10 UWP App Development ebook
Windows 10 UWP App Development ebookWindows 10 UWP App Development ebook
Windows 10 UWP App Development ebook
Cheah Eng Soon
 
How To Embed SlideShare Shows Into WordPress.com
How To Embed SlideShare Shows Into WordPress.comHow To Embed SlideShare Shows Into WordPress.com
How To Embed SlideShare Shows Into WordPress.comKathy Gill
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
SlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
SlideShare
 

Viewers also liked (17)

Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Introducción a Silex. Aprendiendo a hacer las cosas bien en PHP
Introducción a Silex. Aprendiendo a hacer las cosas bien en PHPIntroducción a Silex. Aprendiendo a hacer las cosas bien en PHP
Introducción a Silex. Aprendiendo a hacer las cosas bien en PHP
 
Sales-Funnel-Slideshare
Sales-Funnel-SlideshareSales-Funnel-Slideshare
Sales-Funnel-Slideshare
 
Silex 入門
Silex 入門Silex 入門
Silex 入門
 
Silex入門
Silex入門Silex入門
Silex入門
 
Your marketing funnel is a hot mess
Your marketing funnel is a hot messYour marketing funnel is a hot mess
Your marketing funnel is a hot mess
 
Silex, the microframework
Silex, the microframeworkSilex, the microframework
Silex, the microframework
 
Google drive for nonprofits webinar
Google drive for nonprofits webinarGoogle drive for nonprofits webinar
Google drive for nonprofits webinar
 
&lt;iframe src="//www.slideshare.net/slideshow/embed_code/42392945" width="47...
&lt;iframe src="//www.slideshare.net/slideshow/embed_code/42392945" width="47...&lt;iframe src="//www.slideshare.net/slideshow/embed_code/42392945" width="47...
&lt;iframe src="//www.slideshare.net/slideshow/embed_code/42392945" width="47...
 
Project performance tracking analysis and reporting
Project performance tracking analysis and reportingProject performance tracking analysis and reporting
Project performance tracking analysis and reporting
 
How to Embed a PowerPoint Presentation Using SlideShare
How to Embed a PowerPoint Presentation Using SlideShareHow to Embed a PowerPoint Presentation Using SlideShare
How to Embed a PowerPoint Presentation Using SlideShare
 
Optimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing FunnelOptimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing Funnel
 
Windows 10 UWP App Development ebook
Windows 10 UWP App Development ebookWindows 10 UWP App Development ebook
Windows 10 UWP App Development ebook
 
How To Embed SlideShare Shows Into WordPress.com
How To Embed SlideShare Shows Into WordPress.comHow To Embed SlideShare Shows Into WordPress.com
How To Embed SlideShare Shows Into WordPress.com
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to Silex: From nothing to an API

Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!
cloudbring
 
Sprockets
SprocketsSprockets
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
Dalibor Gogic
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
Perl Careers
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
How we're building Wercker
How we're building WerckerHow we're building Wercker
How we're building Wercker
Micha Hernandez van Leuffen
 
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf Conference
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
Daniel Spector
 
Building websites with Node.ACS
Building websites with Node.ACSBuilding websites with Node.ACS
Building websites with Node.ACS
ralcocer
 
Building websites with Node.ACS
Building websites with Node.ACSBuilding websites with Node.ACS
Building websites with Node.ACS
Ricardo Alcocer
 
Elixir on Containers
Elixir on ContainersElixir on Containers
Elixir on Containers
Sachirou Inoue
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Ondřej Machulda
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsJohn Anderson
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
Laurence Svekis ✔
 
Container (Docker) Orchestration Tools
Container (Docker) Orchestration ToolsContainer (Docker) Orchestration Tools
Container (Docker) Orchestration Tools
Dhilipsiva DS
 
Let's play with adf 3.0
Let's play with adf 3.0Let's play with adf 3.0
Let's play with adf 3.0
Eugenio Romano
 
Puppet and AWS: Getting the best of both worlds
Puppet and AWS: Getting the best of both worldsPuppet and AWS: Getting the best of both worlds
Puppet and AWS: Getting the best of both worlds
Puppet
 
Cocoapods and Most common used library in Swift
Cocoapods and Most common used library in SwiftCocoapods and Most common used library in Swift
Cocoapods and Most common used library in Swift
Wan Muzaffar Wan Hashim
 

Similar to Silex: From nothing to an API (20)

Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!Rapid Prototyping FTW!!!
Rapid Prototyping FTW!!!
 
Sprockets
SprocketsSprockets
Sprockets
 
May The Nodejs Be With You
May The Nodejs Be With YouMay The Nodejs Be With You
May The Nodejs Be With You
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
How we're building Wercker
How we're building WerckerHow we're building Wercker
How we're building Wercker
 
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Building websites with Node.ACS
Building websites with Node.ACSBuilding websites with Node.ACS
Building websites with Node.ACS
 
Building websites with Node.ACS
Building websites with Node.ACSBuilding websites with Node.ACS
Building websites with Node.ACS
 
Elixir on Containers
Elixir on ContainersElixir on Containers
Elixir on Containers
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web apps
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Container (Docker) Orchestration Tools
Container (Docker) Orchestration ToolsContainer (Docker) Orchestration Tools
Container (Docker) Orchestration Tools
 
Let's play with adf 3.0
Let's play with adf 3.0Let's play with adf 3.0
Let's play with adf 3.0
 
Puppet and AWS: Getting the best of both worlds
Puppet and AWS: Getting the best of both worldsPuppet and AWS: Getting the best of both worlds
Puppet and AWS: Getting the best of both worlds
 
Cocoapods and Most common used library in Swift
Cocoapods and Most common used library in SwiftCocoapods and Most common used library in Swift
Cocoapods and Most common used library in Swift
 

Recently uploaded

RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 

Silex: From nothing to an API

  • 1. Silex: From nothing, to an API Sunday, 21 April 13
  • 2. About me I'm Chris Kemper I work at Drummond Central, but I also freelance I've been in the industry for around 5 years I've written a book with a snake on the cover (It's on Version Control, if you didn't know) I also own an elePHPant Sunday, 21 April 13
  • 3. About me Pies Cows Sunday, 21 April 13
  • 4. What is Silex? "Silex is a PHP microframework for PHP 5.3. It is built on the shoulders of Symfony2 and Pimple and also inspired by sinatra." Created by Fabien Potencier and Igor Wiedler Sunday, 21 April 13
  • 5. Getting started You can download it from the site directly http://silex.sensiolabs.org/ Or, you can get with the times and use Composer { "require": { "silex/silex": "1.0.*@dev" ! } } Sunday, 21 April 13
  • 6. Your first end point I’ve used Composer, so after it’s all installed, you can add the first end point! require_once __DIR__.'/../vendor/autoload.php'; $app = new SilexApplication(); $app->get('/hello/{name}', function($name) use($app) { !return 'Hello '.$app->escape($name); }); $app->run(); Sunday, 21 April 13
  • 7. Don’t forget about .htaccess Composer doesn’t pull it down, do don’t forget to put it in. <IfModule mod_rewrite.c> Options -MultiViews RewriteEngine On #RewriteBase /path/to/app RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> If you’re using Apache 2.2.16+, then you can use: FallbackResource /index.php Sunday, 21 April 13
  • 8. nginx works too! server { location = / { try_files @site @site; } location / { try_files $uri $uri/ @site; } location ~ .php$ { return 404; } location @site { fastcgi_pass unix:/var/run/php-fpm/www.sock; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; #fastcgi_param HTTPS on; } } Sunday, 21 April 13
  • 9. Using a templating language You don’t always want to output strings, so let’s use Twig, because it’s awesome. { "require": { "silex/silex": "1.0.*@dev", "twig/twig": ">=1.8,<2.0-dev", "symfony/twig-bridge": "~2.1" } } Sunday, 21 April 13
  • 10. Register the Twig Service provider $app->register(new SilexProviderTwigServiceProvider(), array( ! 'twig.path' => __DIR__.'/views', )); Now to use it $app->get('/hello/{name}', function ($name) use ($app) { !return $app['twig']->render('hello.twig', array( ! 'name' => $name, )); }); Sunday, 21 April 13
  • 11. So many more Service providers Check the docs at http://silex.sensiolabs.org/documentation There are a boat load of Built-in Service Providers which you can take advantage of! Doctrine, Monolog, Form and Validation are just a couple of examples. Sunday, 21 April 13
  • 12. Tips: Extending the base application This allows you to add, anything to the base application to make your own life easier. First of all, you need a class <?php namespace Acme; use SilexApplication as BaseApplication; class Application extends BaseApplication { } Sunday, 21 April 13
  • 13. Tips: Extending the base application Now time to autoload that class, psr-0 style. { "require": { "silex/silex": "1.0.*@dev", "twig/twig": ">=1.8,<2.0-dev", "symfony/twig-bridge": "~2.1"! }, "autoload": { "psr-0": {"Acme": "src/"} } } Sunday, 21 April 13
  • 14. Tips: Separate your config and routes app/bootstrap.php require_once __DIR__ . '/../vendor/autoload.php'; use ! SymfonyComponentHttpFoundationRequest, ! SymfonyComponentHttpFoundationResponse; use ! AcmeApplication; $app = new Application; $app->register(new SilexProviderTwigServiceProvider(), array( ! 'twig.path' => __DIR__.'/views', )); return $app; Sunday, 21 April 13
  • 15. Tips: Separate your config and routes web/index.php <?php $app = include __DIR__ . '/../app/bootstrap.php'; $app->get('/hello/{name}', function ($name) use ($app) { return $app['twig']->render('hello.twig', array( 'name' => $name, )); }); $app->run(); Sunday, 21 April 13
  • 16. Let's make an API Silex is great for API's, so let's make one. Here is the groundwork for a basic user-based API Some lovely endpoints: Create a user (/user) - This will use POST to create a new user in the DB. Update a user (/user/{id}) - This will use PUT to update the user View a user (/user/{id}) - This will use GET to view the users information Delete a user (/user/{id}) - Yes you guessed it, this uses the DELETE method. Sunday, 21 April 13
  • 17. More dependencies! If we want to use a database, we'll need to define one. Let's get DBAL! { "require": { "silex/silex": "1.0.*@dev", "twig/twig": ">=1.8,<2.0-dev", "symfony/twig-bridge": "~2.1", "doctrine/dbal": "2.2.*" }, "autoload": { "psr-0": {"Acme": "src/"} } } Sunday, 21 April 13
  • 18. More dependencies! It'll just be MySQL so let's configure that $app->register(new DoctrineServiceProvider(), array( ! 'db.options' => array( ! ! 'dbname' ! => 'acme', ! ! 'user' ! ! => 'root', ! ! 'password' ! => 'root', ! ! 'host' ! ! => 'localhost', ! ! 'driver' ! => 'pdo_mysql', ! ), )); Sunday, 21 April 13
  • 19. Show me your endpoints: POST Before we can do anything, we need to create some users. $app->post('/user', function (Request $request) use ($app) { $user = array( 'email' => $request->get('email'), ! 'name' => $request->get('name') ); $app['db']->insert('user', $user); return new Response("User " . $app['db']->lastInsertId() . " created", 201); }); Sunday, 21 April 13
  • 20. Show me your endpoints: PUT To update the users, we need to use PUT $app->put('/user/{id}', function (Request $request, $id) use ($app) { $sql = "UPDATE user SET email = ?, name = ? WHERE id = ?"; $app['db']->executeUpdate($sql, array( $request->get('email'), $request->get('name'), (int) $id) ); ! return new Response("User " . $id . " updated", 303); }); Sunday, 21 April 13
  • 21. Show me your endpoints: GET Let's get the API to output the user data as JSON $app->get('/user/{id}', function (Request $request, $id) use ($app) { $sql = "SELECT * FROM user WHERE id = ?"; $post = $app['db']->fetchAssoc($sql, array((int) $id)); return $app->json($post, 201); }); Sunday, 21 April 13
  • 22. Show me your endpoints: DELETE Lastly, we have DELETE $app->delete('/user/{id}', function (Request $request, $id) use ($app) { $sql = "DELETE FROM user WHERE id = ?"; $app['db']->executeUpdate($sql, array((int) $id)); return new Response("User " . $id . " deleted", 303); }); Sunday, 21 April 13
  • 23. A note about match() Using match, you can catch any method used on a route. Like so: $app->match('/user', function () use ($app) { ! ... }); You can also limit the method accepted by match by using the 'method' method $app->match('/user', function () use ($app) { ! ... })->method('PUT|POST'); Sunday, 21 April 13
  • 24. Using before() and after() Each request, can be pre, or post processed. In this case, it could be used for auth. $before = function (Request $request) use ($app) { ... }; $after = function (Request $request) use ($app) { ... }; $app->match('/user', function () use ($app) { ... }) ->before($before) ->after($after); Sunday, 21 April 13
  • 25. Using before() and after() This can also be used globally, like so: $app->before(function(Request $request) use ($app) { ... }); You can also make an event be as early as possible, or as late as possible by using Application::EARLY_EVENT and Application::LATE_EVENT, respectively. $app->before(function(Request $request) use ($app) { ... }, Application::EARLY_EVENT); Sunday, 21 April 13
  • 26. Time for a demo Sunday, 21 April 13
  • 27. Summary This is just a small amount of what Silex is capable of, try it out. Thank You! http://silex.sensiolabs.org/ @chrisdkemper http://chrisdkemper.co.uk Sunday, 21 April 13