$30 off During Our Annual Pro Sale. View Details »

Silex - Symfony goes micro

Silex - Symfony goes micro

Talk on the Silex microframework as given at symfonyday 2011.

Igor Wiedler

October 21, 2011
Tweet

More Decks by Igor Wiedler

Other Decks in Programming

Transcript

  1. View Slide

  2. • phpBB
    • Symfony2
    • Silex
    igorw

    View Slide

  3. View Slide

  4. Silex
    Symfony goes micro
    μ

    View Slide

  5. Silex is not Symfony

    View Slide

  6. Microframework

    View Slide

  7. View Slide

  8. What?
    • Bare bones
    • Routes mapped to controllers
    • The ‘C’ of ‘MVC’
    • REST
    • Single file app

    View Slide

  9. Why?

    View Slide

  10. Sometimes a full-stack framework is
    too much for a simple task.

    View Slide

  11. simple

    View Slide

  12. What makes silex
    special?

    View Slide

  13. • concise
    • extensible
    • testable

    View Slide

  14. • concise
    • extensible
    • testable

    View Slide

  15. • concise
    • extensible
    • testable

    View Slide

  16. • concise
    • extensible
    • testable

    View Slide

  17. • concise
    • extensible
    • testable

    View Slide

  18. Http Kernel
    Interface

    View Slide

  19. Response handle(Request $request)

    View Slide

  20. client

    View Slide

  21. request
    client

    View Slide

  22. reponse
    client
    request

    View Slide

  23. clean

    View Slide

  24. PSR-0

    View Slide

  25. View Slide

  26. Silex is not Symfony

    View Slide

  27. Silex
    is a user interface for
    Symfony

    View Slide

  28. require_once __DIR__.'/silex.phar';
    $app = new Silex\Application();
    $app->get('/', function() {
    return "Hello world!";
    });

    View Slide

  29. Phar
    require_once __DIR__.'/silex.phar';
    $app = new Silex\Application();
    $app->get('/', function() {
    return "Hello world!";
    });

    View Slide

  30. Application
    require_once __DIR__.'/silex.phar';
    $app = new Silex\Application();
    $app->get('/', function() {
    return "Hello world!";
    });

    View Slide

  31. require_once __DIR__.'/silex.phar';
    $app = new Silex\Application();
    $app->get('/', function() {
    return "Hello world!";
    });
    Controller

    View Slide

  32. $app->run();

    View Slide

  33. View Slide


  34. RewriteEngine On
    RewriteBase /some/path
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php [QSA,L]

    View Slide

  35. server {
    location / {
    if (-f $request_filename) {
    break;
    }
    rewrite ^(.*) /index.php last;
    }
    location ~ index\.php$ {
    fastcgi_pass /var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    }
    }

    View Slide

  36. Wait a minute!

    View Slide

  37. Lambdas
    λ

    View Slide

  38. $(function () {
    $("a").click(function (event) {
    alert("Thanks for visiting!");
    });
    });

    View Slide

  39. PHP 5.3

    View Slide

  40. $f = function ($a, $b) {
    return $a + $b;
    };
    $f(1, 2);

    View Slide

  41. lazy
    $f = function () {
    exit;
    };

    View Slide

  42. nested
    $f = function () {
    return function () {
    return true;
    };
    };
    $g = $f();
    $value = $g();

    View Slide

  43. scope
    $outer = 'world';
    $f = function () use ($outer) {
    $inner = 'hello';
    return "$inner $outer";
    };
    => "hello world"

    View Slide

  44. scope
    $helloWorld = function () {
    $outer = 'world';
    $f = function () use ($outer) {
    $inner = 'hello';
    return "$inner $outer";
    };
    return $f();
    }

    View Slide

  45. passing
    $output = function ($info) {
    echo $info."\n";
    };
    $doStuff = function ($output) {
    $output('doing some magic');
    doMagic();
    $output('did some magic');
    };

    View Slide

  46. factory
    $userFactory = function ($name) {
    return new User($name);
    };
    // ...
    $user = $userFactory($_POST['name']);

    View Slide

  47. Usage

    View Slide

  48. $app->get('/', function () {
    return "Hello world!";
    });

    View Slide

  49. Dynamic Routing

    View Slide

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

    View Slide

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

    View Slide

  52. Controllers

    View Slide

  53. assert
    $app->get('/blog/{id}', function ($id) {
    ...
    })
    ->assert('id', '\d+');

    View Slide

  54. value
    $app->get('/{page}', function ($page) {
    ...
    })
    ->value('page', 'index');

    View Slide

  55. bind
    $app->get('/', function () {
    ...
    })
    ->bind('homepage');
    $app['url_generator']->generate('homepage')

    View Slide

  56. bind
    $app->get('/blog/{id}', function ($id) {
    ...
    })
    ->bind('blog_post');
    $app['url_generator']
    ->generate('blog_post', array('id' => $id))

    View Slide

  57. convert
    $app->get('/blog/{post}', function (Post $post) {
    ...
    })
    ->convert('post', function ($post) use ($app) {
    $id = (int) $post;
    return $app['posts']->find($id);
    });

    View Slide

  58. Before & After

    View Slide

  59. $app->before(function () {
    ...
    });
    $app->get('/', function () {
    ...
    });
    $app->after(function () {
    ...
    });

    View Slide

  60. $app->before(function (Request $request) {
    $loggedIn = $request
    ->getSession()
    ->get('logged_in');
    if (!$loggedIn) {
    return new RedirectResponse('/login');
    }
    });

    View Slide

  61. $app->after(function (Request $request, Response $response) {
    // tweak the Response
    });

    View Slide

  62. $app->after(function (
    Request $request,
    Response $response,
    ) use ($app) {
    $response->headers->set('x-csrf-token', $app['csrf_token']);
    });

    View Slide

  63. REST

    View Slide

  64. • get
    • post
    • put
    • delete
    • head
    • options
    • patch

    View Slide

  65. $app->get('/posts/{id}', ...);
    $app->post('/posts', ...);
    $app->put('/posts/{id}', ...);
    $app->delete('/post/{id}', ...);

    View Slide

  66. use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    $app->post('/message', function (Request $request) {
    mail(
    '[email protected]',
    'New message',
    $request->get('body')
    );
    return new Response('Email has been sent!', 201);
    });

    View Slide

  67. Caching

    View Slide

  68. Error Handling

    View Slide

  69. use Symfony\Component\HttpFoundation\Response;
    $app->error(function (\Exception $e, $code) {
    return new Response('Whoops!', $code);
    });

    View Slide

  70. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    throw new NotFoundHttpException("Could not find what you were looking for.");

    View Slide

  71. $app->abort(404, "Could not find the thing.");

    View Slide

  72. $app['debug'] = true;

    View Slide

  73. Redirecting

    View Slide

  74. $app->get('/', function () use ($app) {
    return $app->redirect('/hello');
    });

    View Slide

  75. Pimple

    View Slide

  76. 50 NCLOC

    View Slide

  77. Symfony2 DIC Pimple

    View Slide

  78. Symfony2 DIC Pimple
    Container

    View Slide

  79. Symfony2 DIC Pimple
    Container
    Builder

    View Slide

  80. Symfony2 DIC Pimple
    Container
    Builder
    Extension

    View Slide

  81. Symfony2 DIC Pimple
    Container
    Builder
    Extension
    Loader

    View Slide

  82. Symfony2 DIC Pimple
    Container
    Builder
    Extension
    XML/Yaml
    Loader

    View Slide

  83. Symfony2 DIC Pimple
    Container
    Builder
    Extension
    XML/Yaml
    Compiler
    Loader

    View Slide

  84. Symfony2 DIC Pimple
    Container
    Builder
    Extension
    XML/Yaml
    Compiler
    Loader
    Container

    View Slide

  85. Symfony2 DIC Pimple
    Container
    Builder
    Extension
    XML/Yaml
    Compiler
    Loader
    Container
    ServiceProvider
    ( )

    View Slide

  86. $container = new Pimple();

    View Slide

  87. $app = new Silex\Application();

    View Slide

  88. Parameters
    $app['some_parameter'] = 'value';
    $app['asset.host'] = 'http://cdn.mysite.com/';
    $app['database.dsn'] = 'mysql:dbname=myapp';

    View Slide

  89. Services
    $app['some_service'] = function () {
    return new Service();
    };

    View Slide

  90. $service = $app['some_service'];

    View Slide

  91. Dependencies
    $app['some_service'] = function ($app) {
    return new Service(
    $app['some_other_service'],
    $app['some_service.config']
    );
    };

    View Slide

  92. Shared
    $app['some_service'] = $app->share(function () {
    return new Service();
    });

    View Slide

  93. Protected
    $app['lambda_parameter'] = $app->protect(
    function ($a, $b) {
    return $a + $b;
    });
    // will not execute the lambda
    $add = $app['lambda_parameter'];
    // calling it now
    echo $add(2, 3);

    View Slide

  94. Exposed Services
    • debug
    • request
    • autoloader
    • routes
    • controllers
    • dispatcher
    • resolver
    • kernel

    View Slide

  95. Service Providers

    View Slide

  96. interface ServiceProviderInterface
    {
    function register(Application $app);
    }

    View Slide

  97. Core
    Service Providers
    • doctrine
    • form
    • http cache
    • monolog
    • session
    • swiftmailer
    • symfony bridges
    • translation
    • twig
    • url generator
    • validator

    View Slide

  98. Twig

    View Slide

  99. $app->register(
    new Silex\ServiceProvider\TwigServiceProvider(),
    array(
    'twig.path' => __DIR__.'/views',
    'twig.class_path' => __DIR__.'/vendor/twig/lib',
    )
    );

    View Slide

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

    View Slide

  101. 3rd Party
    • doctrine orm
    • pomm (postgres)
    • predis
    • mongo
    • KyotoTycoon
    • memcache
    • rest
    • markdown
    • gravatar
    • buzz
    • config
    • solr
    • profiler
    • ...

    View Slide

  102. Functional Testing

    View Slide

  103. • src
    • app.php
    • web
    • index.php
    • tests
    • bootstrap.php
    • YourTest.php

    View Slide

  104. src/app.php
    require_once __DIR__.'/../vendor/silex.phar';
    ...
    return $app;

    View Slide

  105. web/index.php
    $app = require_once __DIR__.'/../src/app.php';
    $app->run();

    View Slide

  106. tests/bootstrap.php
    require_once __DIR__.'/../vendor/silex.phar';

    View Slide

  107. use Silex\WebTestCase;
    class YourTest extends WebTestCase
    {
    public function createApp()
    {
    return require __DIR__.'/../src/app.php';
    }
    // tests...
    }
    tests/YourTest.php

    View Slide

  108. public function testAbout()
    {
    $client = $this->createClient();
    $client->request('GET', '/about');
    $response = $client->getResponse();
    $this->assertTrue($response->isOk());
    $this->assertContains('trashbin',
    $response->getContent());
    $this->assertContains('github',
    $response->getContent());
    $this->assertContains('igorw',
    $response->getContent());
    }

    View Slide

  109. phpunit.xml.dist

    backupStaticAttributes="false"
    colors="true"
    convertErrorsToExceptions="true"
    convertNoticesToExceptions="true"
    convertWarningsToExceptions="true"
    processIsolation="false"
    stopOnFailure="false"
    syntaxCheck="false"
    bootstrap="tests/bootstrap.php"
    >


    ./tests/



    View Slide

  110. $ phpunit

    View Slide

  111. View Slide

  112. View Slide

  113. • smallish sites
    • well-defined scope
    • prototyping
    • restful apis
    When to use

    View Slide

  114. and many more...

    View Slide

  115. The future

    View Slide

  116. The future
    • Cookbooks

    View Slide

  117. The future
    • Cookbooks
    • Best practices

    View Slide

  118. The future
    • Cookbooks
    • Best practices
    • Symfony2 integration

    View Slide

  119. The future
    • Cookbooks
    • Best practices
    • Symfony2 integration
    • FOSUserBundle

    View Slide

  120. The future
    • Cookbooks
    • Best practices
    • Symfony2 integration
    • FOSUserBundle
    • Composer

    View Slide

  121. on github
    fabpot/Silex
    fabpot/Pimple

    View Slide

  122. silex.sensiolabs.org

    View Slide

  123. Ω

    View Slide

  124. Questions?
    joind.in/3699
    @igorwesome
    speakerdeck.com
    /u/igorw

    View Slide