Slide 1

Slide 1 text

Taming Runaway Silex Apps http://www.flickr.com/photos/tal_axl/4321730058

Slide 2

Slide 2 text

@davedevelopment childcare.co.uk

Slide 3

Slide 3 text

Legacy http://www.flickr.com/photos/14993459@N08/5704123809

Slide 4

Slide 4 text

Pimple + Services http://www.flickr.com/photos/wikidave/7440588732/sizes/l/

Slide 5

Slide 5 text

Silex

Slide 6

Slide 6 text

Organised Chaos

Slide 7

Slide 7 text

Intro Best Practices Conventions Extensions Performance

Slide 8

Slide 8 text

Don’t listen to me

Slide 9

Slide 9 text

Pimple A simple Dependency Injection Container for PHP 5.3

Slide 10

Slide 10 text

Silex Pimple

Slide 11

Slide 11 text

$app['kernel'] = function ($app) { return new HttpKernel( $app['dispatcher'], $app['resolver'], $app['request_stack'] ); };

Slide 12

Slide 12 text

class Pimple implements ArrayAccess { function share($callable); function protect($callable); function raw($id); function extend($id, $callable); function keys(); }

Slide 13

Slide 13 text

class Pimple implements ArrayAccess { function share($callable); function protect($callable); function raw($id); function extend($id, $callable); function keys(); }

Slide 14

Slide 14 text

Namespace everything $app['twig'] = ... $app['twig.loader'] = ... $app['twig.loader.filesystem'] = ...

Slide 15

Slide 15 text

Lazyness The lazy way of spelling "laziness"

Slide 16

Slide 16 text

The Problem

Slide 17

Slide 17 text

// user.repository gets defined $app['user.repository'] = $app->share(function() { return new UserRepository(); });

Slide 18

Slide 18 text

// user.service depends on user.repository $app['user.service'] = $app->share(function($app) { return new UserService($app['user.repository']); });

Slide 19

Slide 19 text

// user.service is accessed $app['user.service']->setOption('debug', true);

Slide 20

Slide 20 text

// user.repository is redefined/extended $app['user.repository'] = $app->share($app->extend( 'user.repository', function ($repo) { return new CachingRepository($repo); } )); // but user.service already has the uncached version $app['user.service']-> ....

Slide 21

Slide 21 text

Theoretical Lifecycle

Slide 22

Slide 22 text

Compile Time Defining Services

Slide 23

Slide 23 text

Do not access any services until all services have been registered

Slide 24

Slide 24 text

Compile Time Extending Services

Slide 25

Slide 25 text

Do not access any services until all services have been extended as required

Slide 26

Slide 26 text

Runtime Accessing Services

Slide 27

Slide 27 text

Do not redefine services once they have been accessed

Slide 28

Slide 28 text

Pimple 2.0 Services are frozen once accessed

Slide 29

Slide 29 text

Performance Everything adds up

Slide 30

Slide 30 text

Lazyness helps a lot...

Slide 31

Slide 31 text

...but the container is “recompiled” for every request

Slide 32

Slide 32 text

app/console cache:clear

Slide 33

Slide 33 text

Pimple 2.0 Major performance improvements

Slide 34

Slide 34 text

Not everything has to be defined as a service Extract when necessary

Slide 35

Slide 35 text

$app['sw.service'] = $app->share(function($app) { return new Stopwords\Service( $app['sw.repo'] ); }); $app['sw.repo'] = $app->share(function($app) { return new Stopwords\Repository($app['db']); });

Slide 36

Slide 36 text

$app['sw.service'] = $app->share(function($app) { return new Stopwords\Service( new Stopwords\Repository($app['db']) ); });

Slide 37

Slide 37 text

Auto-wiring

Slide 38

Slide 38 text

boundTypes[$type] = $service; } public function resolve($type, array $fixedArgs = array()) { $boundTypes = &$this->boundTypes; return function ($app) use ($type, &$boundTypes, $fixedArgs) { $rfc = new \ReflectionClass($type); $ctor = $rfc->getConstructor(); $args = array(); foreach ($ctor->getParameters() as $param) { $classHint = $param->getClass()->getName(); if ($classHint) { if (isset($boundTypes[$classHint])) { $args[] = $app[$boundTypes[$classHint]]; } else if (isset($app[$classHint])) { $args[] = $app[$classHint]; } else if (isset($app[$param->getName()])) { $args[] = $app[$param->getName()]; } else { throw new \RuntimeException("Could not resolve service for $classHint"); } } else { if (isset($fixedArgs[$param->getName()])) { $args[] = $fixedArgs[$param->getName]; } else { throw new \RuntimeException("Could not resolve parameter for {$param->getName} for $type"); } } } return $rfc->newInstanceArgs($args); }; } } ~50 slocs Could do with some caching

Slide 39

Slide 39 text

// Acme\User\Service\Authentication public function __construct(UserRepository $userRepo) { $this->repo = $userRepo; } // usage $app->bindType( 'Acme\User\Repository\UserRepository', 'user.repository' ); $app['user.service'] = $app->resolve( 'Acme\User\Service\Authentication' );

Slide 40

Slide 40 text

Silex The PHP micro-framework based on the Symfony2 Components

Slide 41

Slide 41 text

$app = new Silex\Application; $app->get("/hello/{name}", function ($name, $app) { return "Hello" . $app->escape($name); }); $app->run();

Slide 42

Slide 42 text

Silex exposes an intuitive and concise API that is fun to use

Slide 43

Slide 43 text

function get($pattern, $to = null); function post($pattern, $to = null); function put($pattern, $to = null); function delete($pattern, $to = null); function match($pattern, $to = null);

Slide 44

Slide 44 text

function get($pattern, $to = null); function post($pattern, $to = null); function put($pattern, $to = null); function delete($pattern, $to = null); function match($pattern, $to = null);

Slide 45

Slide 45 text

function before($callback, $priority = 0); function after($callback, $priority = 0); function finish($callback, $priority = 0); function error($callback, $priority = -8); function on($eventName, $callback, $priority = 0);

Slide 46

Slide 46 text

function before($callback, $priority = 0); function after($callback, $priority = 0); function finish($callback, $priority = 0); function error($callback, $priority = -8); function on($eventName, $callback, $priority = 0);

Slide 47

Slide 47 text

Silex defines a range of services which can be used or replaced You probably don't want to mess with most of them

Slide 48

Slide 48 text

Silex HttpKernelInterface {abstract} HttpKernel Routing EventDispatcher HttpFoundation

Slide 49

Slide 49 text

Service Providers

Slide 50

Slide 50 text

$app = new Silex\Application; $app->register( new Silex\Provider\TwigServiceProvider(), [ 'twig.path' => __DIR__.'/views', ] );

Slide 51

Slide 51 text

symfony/security symfony/form symfony/translation symfony/validator twig/twig doctrine/dbal swiftmailer/swiftmailer monolog/monolog

Slide 52

Slide 52 text

doctrine/orm mustache/mustache kriswallsmith/assetic guzzle/guzzle imagine/imagine symfony/web-profiler-bundle jms/serializer aws/aws-sdk-php

Slide 53

Slide 53 text

File Structure

Slide 54

Slide 54 text

web/ # assets + front controllers app/ # app config/bootstrap src/ # app code bin/ # cli scripts + binstubs

Slide 55

Slide 55 text

app/ config/ views/ app.php controllers.php # optional

Slide 56

Slide 56 text

get('/', function() { return 'Hello'; } return $app;

Slide 57

Slide 57 text

> export APPLICATION_ENV=production > psysh app/app.phpT Psy Shell v0.1.0-dev (PHP 5.4.9 — cli) by Justin Hileman >>> $app[‘user.service’]->deleteAll(...

Slide 58

Slide 58 text

web/ assets/ index.php index_dev.php # optional

Slide 59

Slide 59 text

src/ Acme/ functions.php WebApp/ ServiceProvider.php User/ Service/ Authentication.php Email/ Service/ Mailer.php

Slide 60

Slide 60 text

Writing Service Providers

Slide 61

Slide 61 text

namespace Silex; interface ServiceProviderInterface { public function register(Application $app); public function boot(Application $app); }

Slide 62

Slide 62 text

register() is for registering parameters and services

Slide 63

Slide 63 text

Do register parameters preferably defaults

Slide 64

Slide 64 text

Do register services

Slide 65

Slide 65 text

Do extend services

Slide 66

Slide 66 text

Don’t access services

Slide 67

Slide 67 text

Don’t do anything else

Slide 68

Slide 68 text

boot() is for doing things before handling a request Usually adding event listeners

Slide 69

Slide 69 text

Generally acceptable to access services here Try not to

Slide 70

Slide 70 text

Silex 2.0 [Experimental] boot() is moved to a separate provider interface

Slide 71

Slide 71 text

Controller Providers

Slide 72

Slide 72 text

namespace Silex; interface ControllerProviderInterface { function connect(Application $app); }

Slide 73

Slide 73 text

// Acme/Silex/ControllerProvider public function connect(Application $app) { $controllers = $app['controllers_factory']; $controllers->get( '/hello/{name}', function ($name, Application $app) { return 'Hello'.$app->escape($name); } )->bind('site.hello_world'); return $controllers; } // app/app.php $app->mount('/', new SiteControllerProvider());

Slide 74

Slide 74 text

Modules Bundles, Packages...

Slide 75

Slide 75 text

src/Acme/User/ServiceProvider.php src/Acme/User/ControllerProvider.php

Slide 76

Slide 76 text

namespace Acme\User; use Silex\Application; use Silex\ControllerProviderInterface; use Silex\ServiceProviderInterface; class Provider implements ControllerProviderInterface, ServiceProviderInterface { public function register(Application $app) {} public function boot(Application $app) {} public function connect(Application $app) {} }

Slide 77

Slide 77 text

// Acme\User\Module public static function register(Application $app) { $app->register(new ServiceProvider()); $app->mount('/', new ControllerProvider()); $app->mount('/', new AdminControllerProvider()); } // app/app.php Acme\User\Module::register($app);

Slide 78

Slide 78 text

Controllers

Slide 79

Slide 79 text

Name(space) all routes Silex default mirrors the pattern

Slide 80

Slide 80 text

$app->get( '/hello/{name}', function ($name, Application $app) { return "Hello" . $app->escape($name); } )->bind('site.welcome');

Slide 81

Slide 81 text

> bin/routes site.welcome GET /hello/{name} app/app.php:12

Slide 82

Slide 82 text

Anonymous Functions

Slide 83

Slide 83 text

Named Functions

Slide 84

Slide 84 text

function welcome($name, Application $app) { return "Hello " . $app->escape($name); }; $app->get('/hello/{name}', 'welcome') ->bind('site.welcome');

Slide 85

Slide 85 text

$app = mock('Silex\Application'); $app->shouldReceive('escape') ->with('Bob') ->andReturn('Dave'); assertThat( welcome('Bob', $app), equalTo('Hello Dave') );

Slide 86

Slide 86 text

Controllers as Classes

Slide 87

Slide 87 text

// Acme\Controller\SiteController public function welcome($name, Application $app) { return 'Hello ' . $app->escape($name); } // Acme\ControllerProvider.php $app->get( '/hello/{name}', 'Acme\Controller\SiteController::welcome' )->bind('site.welcome');

Slide 88

Slide 88 text

// S\C\HttpKernel\Controller\ControllerResolver list($class, $method) = explode('::', $controller, 2); return array(new $class(), $method);

Slide 89

Slide 89 text

Injecting the container BaseController and helpers

Slide 90

Slide 90 text

// class BaseControllerResolver list($class, $method) = explode('::', $controller, 2); $controller = new $class(); if ($controller instanceof BaseController) { $controller->setApplication($app); } return array($controller, $method);

Slide 91

Slide 91 text

$app['resolver'] = $this->share($app->extend( 'resolver', function ($resolver, $app) { return new BaseControllerResolver( $resolver, $app ); } ));

Slide 92

Slide 92 text

// abstract class BaseController public function setApplication(Application $app) { $this->app = $app; } public function get($key) { return $this->app[$key]; }

Slide 93

Slide 93 text

// abstract class BaseController public function render($template, array $context) { return $this ->get('twig') ->render($template, $context); }

Slide 94

Slide 94 text

class SiteController extends BaseController { public function welcome($name) { $user = $this ->get('user.repository') ->findByName($name); return $this->render( 'user.html.twig', [ 'user' => $user, 'name' => $name, ] ); } }

Slide 95

Slide 95 text

class SiteController extends BaseController { public function welcome($name) { $user = $this ->get('user.repository') ->findByName($name); return $this->render( 'user.html.twig', [ 'user' => $user, 'name' => $name, ] ); } }

Slide 96

Slide 96 text

class SiteController extends BaseController { public function welcome($name) { $user = $this ->get('user.repository') ->findByName($name); return $this->render( 'user.html.twig', [ 'user' => $user, 'name' => $name, ] ); } }

Slide 97

Slide 97 text

Controllers as Services

Slide 98

Slide 98 text

use Silex\Provider\ServiceControllerServiceProvider; $app->register( new ServiceControllerServiceProvider(), ); $app['site.controller'] = $app->share(function($app) { return new Acme\Controller\SiteController( $app['user.repository'], $app['twig'] ); }); $app->get('/hello/{name}', 'site.controller:welcome') ->bind('site.welcome');

Slide 99

Slide 99 text

use Silex\Provider\ServiceControllerServiceProvider; $app->register( new ServiceControllerServiceProvider(), ); $app['site.controller'] = $app->share(function($app) { return new Acme\Controller\SiteController( $app['user.repository'], $app['twig'] ); }); $app->get('/hello/{name}', 'site.controller:welcome') ->bind('site.welcome');

Slide 100

Slide 100 text

use Silex\Provider\ServiceControllerServiceProvider; $app->register( new ServiceControllerServiceProvider(), ); $app['site.controller'] = $app->share(function($app) { return new Acme\Controller\SiteController( $app['user.repository'], $app['twig'] ); }); $app->get('/hello/{name}', 'site.controller:welcome') ->bind('site.welcome');

Slide 101

Slide 101 text

// Acme\Controller\SiteController public function __construct($repo, $twig) { $this->repo = $repo; $this->twig = $twig; } public function welcome($name) { $user = $this->repo->find($name); return $this->twig->render( 'user.html.twig', [ 'user' => $user, 'name' => $name ] ); }

Slide 102

Slide 102 text

// Acme\Controller\SiteController public function __construct($repo, $twig) { $this->repo = $repo; $this->twig = $twig; } public function welcome($name) { $user = $this->repo->find($name); return $this->twig->render( 'user.html.twig', [ 'user' => $user, 'name' => $name, ] ); }

Slide 103

Slide 103 text

Resource based Routing RAD

Slide 104

Slide 104 text

Name Method Pattern Controller Method users.index GET /users indexAction users.new GET /users/new newAction users.create POST /users newAction users.show GET /users/{id} showAction($id) users.edit GET /users/{id}/edit editAction($id) users.update PUT /users/{id} editAction($id) users.delete DELETE /users/{id} deleteAction($id)

Slide 105

Slide 105 text

function resource($path, $ns, $service, $app) { $app->get($path, "$service:indexAction") ->bind("$ns.index"); $app->get($path."/{id}", "$service:showAction") ->bind("$ns.show"); $app->put($path."/{id}", "$service:updateAction") ->bind("$ns.update"); /* ... */ } resource("/users", "users", "users.controller", $app); resource("/posts", "posts", "posts.controller", $app);

Slide 106

Slide 106 text

Performance Everything adds up

Slide 107

Slide 107 text

Silex doesn’t use the full Router, only the UrlMatcher Routes are “recompiled” for every request

Slide 108

Slide 108 text

Laravel 4.1 features a totally re-written routing layer. The API is the same; however, registering routes is a full 100% faster compared to 4.0. The entire engine has been greatly simplified, and the dependency on Symfony Routing has been removed.

Slide 109

Slide 109 text

if (false == getenv('SKIP_ADMIN_CONTROLLERS')) { $app->mount( '/', new AdminPanelControllerProvider() ); }

Slide 110

Slide 110 text

No content

Slide 111

Slide 111 text

/flint/flint Enhancements to Silex with structure and conventions.

Slide 112

Slide 112 text

Replaces the UrlMatcher with the full Router At the cost of some flexibility

Slide 113

Slide 113 text

Event Listeners

Slide 114

Slide 114 text

Use the shortcut methods like $app->on()

Slide 115

Slide 115 text

Just like controllers anonymous functions are good, services are better

Slide 116

Slide 116 text

Performance Lazyness

Slide 117

Slide 117 text

function lazy($app, $service, $method) { return function() use ($app, $service, $method) { return call_user_func_array( [$app[$service], $method], func_get_args() ); }; } $app->on( AppEvents::USER_UPGRADE, lazy($app, "user.event_logger", "onUserEvent") );

Slide 118

Slide 118 text

// Silex 1.2 $app->on( AppEvents::USER_UPGRADE, "user.event_logger:onUserEvent" );

Slide 119

Slide 119 text

/davedevelopment/ pimple-aware-event-dispatcher

Slide 120

Slide 120 text

$app['dispatcher'] = $app->share($app->extend( 'dispatcher', function($dispatcher) use ($app) { return new PimpleAwareEventDispatcher( $dispatcher, $app ); } )); $app['dispatcher']->addSubscriberService( “user.event_logger", "Acme\User\EventLogger" );

Slide 121

Slide 121 text

View Renderers

Slide 122

Slide 122 text

// Acme\Controller\UserController public function showAction($id) { $user = $this->repo->find($id); return ['user' => $user]; } $app->get('/user/{id}', 'user.controller:showAction') ->value('template', 'user.html.twig');

Slide 123

Slide 123 text

// Acme\Controller\UserController public function showAction($id) { $user = $this->repo->find($id); return ['user' => $user]; } $app->get('/user/{id}', 'user.controller:showAction') ->value('template', 'user.html.twig');

Slide 124

Slide 124 text

// Acme\Controller\UserController public function showAction($id) { $user = $this->repo->find($id); return ['user' => $user]; } $app->get('/user/{id}', 'user.controller:showAction') ->value('template', 'user.html.twig');

Slide 125

Slide 125 text

$app->on(KernelEvents::VIEW, function ($e) use ($app) { $view = $e->getControllerResult(); if (!is_array($view)) { return; } $request = $event->getRequest(); $template = $request->attributes->get('template'); $body = $app['twig']->render($template, $view); $e->setResponse(new Response($body)); });

Slide 126

Slide 126 text

$app->on(KernelEvents::VIEW, function ($e) use ($app) { $view = $e->getControllerResult(); if (!is_array($view)) { return; } $request = $event->getRequest(); $template = $request->attributes->get('template'); $body = $app['twig']->render($template, $view); $e->setResponse(new Response($body)); });

Slide 127

Slide 127 text

$app->on(KernelEvents::VIEW, function ($e) use ($app) { $view = $e->getControllerResult(); if (!is_array($view)) { return; } $request = $event->getRequest(); $template = $request->attributes->get('template'); $body = $app['twig']->render($template, $view); $e->setResponse(new Response($body)); });

Slide 128

Slide 128 text

$app->on(KernelEvents::VIEW, function ($e) use ($app) { $view = $event->getControllerResult(); if (!is_array($view)) { return; } $request = $event->getRequest(); // user.show.html.twig $template = $request->attributes->get('_route'); $template.= ".html.twig"; $body = $app['twig']->render($template, $view); $event->setResponse(new Response($body)); });

Slide 129

Slide 129 text

Summary •Treat a Silex app like any other app •Pimple requires care when you have a lot of services •Namespace and name everything •Lazyness for as much as possible •Silex’ API is narrow, scope widens when you dig around inside •Silex has to do a lot of work for every request, grows linearly with your app

Slide 130

Slide 130 text

@davedevelopment [email protected] joind.in/10374 #silex-php Questions?

Slide 131

Slide 131 text

Further Reading https://igor.io/2013/09/02/how-heavy-is- silex.html http://srcmvn.com/blog/2013/03/08/silex- service-providers-and-controller-providers- what-is-safe-to-do-where/ https://igor.io/2012/11/09/scaling-silex.html

Slide 132

Slide 132 text

Honorary mention /dcousineau/orlex