Slide 1

Slide 1 text

What Symfony Components can do for you. php[tek] 2013 Chicago, May 15th Andreas Hucks

Slide 2

Slide 2 text

@meandmymonkey Andreas Hucks Trainer & Consultant at SensioLabs Deutschland

Slide 3

Slide 3 text

Symfony 2.0 Is a Full Stack Framework ...

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

... not only.

Slide 6

Slide 6 text

Symfony2 is a reusable set of standalone, decoupled, and cohesive PHP 5.3 components that solve common web development problems.

Slide 7

Slide 7 text

Stuff built using SF2 Components (to varying degrees) • Symfony2 (duh) • Drupal 8 • Silex • Laravel • PPI • PHPUnit • Composer • ... I probably forgot something important

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

if  ($_GET['action']  ==  'close') {        $query  =  'UPDATE  todo  SET  is_done  =  1  WHERE  id  =  '.  mysql_real_escape_string($_GET['id']);        mysql_query($query,  $conn)  or  die('Unable  to  update  existing  task  :  '.  mysql_error());        header('Location:  /app.php/'); } $result  =  mysql_query('SELECT  COUNT(*)  FROM  todo',  $conn); $count    =  current(mysql_fetch_row($result)); $result  =  mysql_query('SELECT  *  FROM  todo',  $conn) ?>        ';                        echo  '    '.  $todo['id']  .'';                        echo  '    '.  $todo['title']  .'';                        echo  '    '; 4.0 TM

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

HttpFoundation

Slide 14

Slide 14 text

HttpFoundation • OOP Interface for HTTP • No more Superglobals • Helper Methods

Slide 15

Slide 15 text

Legacy Wrapper public  function  execute($file,  Request  $request) {        $file  =  $this-­‐>basePath  .  $file;        if  (!is_file($file)  &&  someSanityCheck($file))  {                throw  new  \Exception('Invalid  controller.');        }        extract($this-­‐>context);        ob_start();        require_once  $this-­‐>basePath  .  $file;        return  new  Response(ob_get_clean()); }

Slide 16

Slide 16 text

web/app.php use  Legacy\Wrapper; use  Symfony\Component\Debug\Debug; use  Symfony\Component\HttpFoundation\Request; $wrapper  =  new  Wrapper(__DIR__  .  '/../legacy'); $request  =  Request::createFromGlobals(); $response  =  $wrapper-­‐>execute(        $request-­‐>getPathInfo(),        $request ); $response-­‐>send();

Slide 17

Slide 17 text

Testability & Compatibility $request  =  Request::createFromGlobals(); $response  =  doSomethingToGenerateResponse($request); $response-­‐>send();

Slide 18

Slide 18 text

No content

Slide 19

Slide 19 text

Wrap Up • Starting point for refactoring: • Isolated legacy code • Can now be integrated into new app • Testable!

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

Debug

Slide 23

Slide 23 text

Debug • Error Handler • Exception Handler • Error Logging (optionally)

Slide 24

Slide 24 text

Error Handler ErrorHandler::register($level  =  null); ErrorHandler::setLogger(LoggerInterface  $logger  =  null);

Slide 25

Slide 25 text

Exception Handler ExceptionHandler::register($debug  =  true);

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

Debug Debug::enable($level  =  null);

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

Routing

Slide 31

Slide 31 text

Routing • Define routes as patterns • Assign attributes • Match an incoming URI to a route • Generate an URI from a route object

Slide 32

Slide 32 text

Defining a Route $routeHome  =  new  Route('/index.php'); $routeHome-­‐>setDefault(        '_controller',        function(Request  $request)  use  ($wrapper)        {                return  $wrapper-­‐>execute('/index.php',  $request);        } );

Slide 33

Slide 33 text

Matching $routes  =  new  RouteCollection(); $routes-­‐>add('list',  $routeHome); //  ... $context  =  new  RequestContext(); $context-­‐>fromRequest($request); $matcher  =  new  UrlMatcher($routes,  $context); $parameters  =  $matcher-­‐>match($request-­‐>getPathInfo());

Slide 34

Slide 34 text

Parameters? $routeHome-­‐>setDefault('_controller',  'MyController'); $routeHome-­‐>setDefault('page',  1); $routes-­‐>add('list',  $routeHome); array  (        '_controller'  =>  'MyController',        '_route'            =>  'list',        'page'                =>  1 )

Slide 35

Slide 35 text

Determine Controller $parameters  =  $matcher-­‐>match($request-­‐>getPathInfo()); $response  =  $parameters['_controller']($request); $response-­‐>send();

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

Templating

Slide 40

Slide 40 text

• Simple, extensible templating engine • PHP! • Escaping, Inheritance • Generic Interface to allow for easy engine replacement (Twig!)

Slide 41

Slide 41 text

       [...]  / / here be dragons 4.0 TM

Slide 42

Slide 42 text

layout.php [...]
       output('content');  ?>
[...]

Slide 43

Slide 43 text

list.php extend('layout.php')  ?> start('content')  ?>        [...]                                                                        /td>                                [...]                                                [...] stop()  ?>

Slide 44

Slide 44 text

Rendering $templating  =  new  PhpEngine(        new  TemplateNameParser(),        new  FilesystemLoader(                array(__DIR__  .  '/../templates/%name%')        ) ); $html  =  $templating-­‐>render(    'list.php',    array(            'tasks'  =>  $tasks    ) );

Slide 45

Slide 45 text

Inside the Controller public  function  listAction(Request  $request) {        //  load  tasks  from  db        return  new  Response(                $this-­‐>templating-­‐>render(                      'list.php',                      array(                          'urlGenerator'  =>  $router-­‐>getGenerator(),                          'tasks'                =>  $tasks                  )          )      ); }

Slide 46

Slide 46 text

Generating URLs [...] [...]

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

The all-in-one Router $context  =  new  RequestContext(); $context-­‐>fromRequest($request); $locator  =  new  FileLocator(__DIR__  .  '/../config'); $router  =  new  Router(        new  YamlFileLoader($locator),        'routing.yml',        array(                'cache_dir'  =>  __DIR__  .  '/../cache'        ),        $context );

Slide 50

Slide 50 text

YAML Configuration list:        pattern:  /        methods:  GET        defaults:  {  _controller:  list  } show:        pattern:  /{id}        methods:  GET        defaults:  {  _controller:  show  } create:        pattern:  /        methods:  POST        defaults:  {  _controller:  create  }

Slide 51

Slide 51 text

Matcher and Generator $urlGenerator  =  $router-­‐>getGenerator(); $matcher  =  $router-­‐>getMatcher();

Slide 52

Slide 52 text

Call the (new) Controller $controller  =  //  create  controller  instance $parameters  =  $matcher-­‐>match($request-­‐>getPathInfo()); $response  =  call_user_func(   array(     $controller,     $parameters['_controller']  .  'Action'   ),   $request ); $response-­‐>send();

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

HttpKernel

Slide 56

Slide 56 text

HttpKernel • Provides a predefined workflow to convert a Request into a Response • Events to hook into • Error Logging (optionally)

Slide 57

Slide 57 text

Let the kernel handle it. $dispatcher  =  new  EventDispatcher(); $dispatcher-­‐>addSubscriber(        new  RouterListener($router-­‐>getMatcher()) ); $resolver  =  new  MyControllerResolver($controller); $kernel  =  new  HttpKernel($dispatcher,  $resolver); $request  =  Request::createFromGlobals(); $response  =  $kernel-­‐>handle($request); $response-­‐>send();

Slide 58

Slide 58 text

Controller Resolver? interface  ControllerResolverInterface {      public  function  getController(Request  $request);      public  function  getArguments(Request  $request,  $controller); }

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

A look back $request  =  Request::createFromGlobals(); $response  =  $kernel-­‐>handle($request);

Slide 62

Slide 62 text

BrowserKit & CssSelector

Slide 63

Slide 63 text

Base Test use  Symfony\Component\HttpKernel\Client; class  FunctionalTestCase  extends  \PHPUnit_Framework_TestCase {        protected  static  function  createClient()        {                $kernel  =  //  somehow  create  a  kernel                return  new  Client($kernel);        } }

Slide 64

Slide 64 text

A Test Case class  IndexPageTest  extends  FunctionalTestCase {        public  function  testList()        {                $client  =  static::createClient();                $crawler  =  $client-­‐>request('GET',  '/');                $this-­‐>assertEquals(200,  $client-­‐>getResponse()-­‐>getStatusCode());                $this-­‐>assertCount(1,  $crawler-­‐>filter('h1:contains("My  Todos  List")'));        } }

Slide 65

Slide 65 text

Testing Forms $form  =  $crawler-­‐>selectButton('send')-­‐>form(); $client-­‐>submit($form,  array('title'  =>  'MyTask')); $this-­‐>assertEquals(302,  $client-­‐>getResponse()-­‐>getStatusCode()); $crawler  =  $client-­‐>followRedirect(); $this-­‐>assertCount(1,  $crawler-­‐>filter(sprintf('a:contains("%s")',  'MyTask')));

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

Config & Yaml

Slide 69

Slide 69 text

Config • Locating, Loading, Caching of config files • Validation of config files • Merging of cascading config sets

Slide 70

Slide 70 text

Loading Configuration Data $configPath  =  __DIR__  .  '/../config/config.yml'; $config  =  Yaml::parse($configPath);

Slide 71

Slide 71 text

Loading Configuration Data $cachePath  =  __DIR__  .  '/../cache/config.php'; $configPath  =  __DIR__  .  '/../config/config.yml'; $configCache  =  new  ConfigCache($cachePath,  true); if  (!$configCache-­‐>isFresh())  {        $resource  =  new  FileResource($configPath);        $code  =  'write($code,  array($resource)); } $config  =  require  $cachePath;

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

Console

Slide 74

Slide 74 text

Console • Easy setup for CLI scripts • Output formatting, help system • Interactive dialogs

Slide 75

Slide 75 text

Commands use  Symfony\Component\Console\Command\Command; class  AddTaskCommand  extends  Command {        public  function  configure()        {                $this-­‐>setName('todo:add');                $this-­‐>setDescription('Add  a  new  task  to  your  todo  list');                $this-­‐>addArgument('title',  InputArgument::OPTIONAL,  'The  task  title');        }        //  ... }

Slide 76

Slide 76 text

The Application use  Symfony\Component\Console\Application; $db  =  //  create  PDO  instance $app  =  new  Application('Todo  List  Helpers'); $app-­‐>add(new  AddTaskCommand($db)); $app-­‐>add(new  ExpireTasksCommand($db)); $app-­‐>run();

Slide 77

Slide 77 text

No content

Slide 78

Slide 78 text

No content

Slide 79

Slide 79 text

Execution public  function  execute(InputInterface  $input,  OutputInterface  $output) {        $dialog  =  $this-­‐>getHelperSet()-­‐>get('dialog');        $title  =  $dialog-­‐>ask(                $output,                'What  do  you  have  to  do?  '        );        if  ($title)  {                //  do  stuff                $output-­‐>writeln('Task  created.');        }  else  {                $output-­‐>writeln('No  input  given!');        } }

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

What else is there? • Form • Security • Validator • Event Dispatcher • Finder • Process • PropertyAccess • OptionsResolver • ...

Slide 83

Slide 83 text

Go forth and learn! http://goo.gl/a0bCJ

Slide 84

Slide 84 text

Thanks! Questions? Please give feedback: http://goo.gl/IMK9n