Slide 1

Slide 1 text

Symfony components in the wild Jakub Zalas

Slide 2

Slide 2 text

What is Symfony?

Slide 3

Slide 3 text

http://symfony.com/projects

Slide 4

Slide 4 text

Projects on packagist.org 4373 21% 1206 6% 14838 73% Depends on Symfony Depends on Zend Other

Slide 5

Slide 5 text

0 100 200 300 400 500 600 700 Bundles Other Symfony Component based projects

Slide 6

Slide 6 text

Fixing PHP Debug HttpFoundation Yaml Tools Filesystem Finder Process Stopwatch Web Framework Foundation HttpKernel Routing Templating Data Helpers Config OptionsResolver PropertyAccess Serializer Patterns DependencyInjection   EventDispatcher   I18n Intl + Icu Locale Translation Crawlers BrowserKit CssSelector DomCrawler Framework+ ClassLoader Console ExpressionLanguage Form Security Validator

Slide 7

Slide 7 text

Fixing PHP

Slide 8

Slide 8 text

HttpFoundation

Slide 9

Slide 9 text

$_GET $_POST $_SERVER $_COOKIE $_FILES

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals(); $request->query $request->request $request->server $request->cookies $request->files $request->headers $request->attributes

Slide 12

Slide 12 text

$id = isset($_GET['id']) ? $_GET['id'] : -1; becomes $id = $request->query->get('id', -1);

Slide 13

Slide 13 text

use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals(); $request->attributes->set('id', 15); function myController (Request $request) { $id = $request->attributes->get('id'); // do your stuff }

Slide 14

Slide 14 text

$expiresAt = new \DateTime('+1hour'); $expiresAt->setTimezone( new \DateTimeZone('UTC') ); $expires = $expresAt->format('D, d M Y H:i:s'); $expires.= ' GMT’; header('X-Event: SymfonyCon'); header('Cache-Control: public'); header('Expires: '.$expires); echo 'Hello!';

Slide 15

Slide 15 text

use Symfony\Component\HttpFoundation\Response; $response = new Response('Hello!', 200); $response->headers->set('X-Event', 'SymfonyCon'); $response->setPublic(); $response->setExpires(new \DateTime('+1hour')); $response->send();

Slide 16

Slide 16 text

// Somewhere in a controller $id = $request->query->get('id'); $date = $this->getPageUpdatedAtById($id); $response = new Response(); $response->setPublic(); $response->setLastModified($date); if ($response->isNotModified($request)) { return $response; } // else do heavy processing to render the page

Slide 17

Slide 17 text

in the wild…

Slide 18

Slide 18 text

use Symfony\Component\HttpFoundation\Request; $request = Request::createFromGlobals(); $configuration = new \Proxy\Configuration(); $configuration->setBackend('nousefreak.be'); $proxy = new \Proxy\Proxy(); $proxy->setConfiguration($configuration); $response = $proxy->proxy($request); $response->send(); nousefreak/proxy  

Slide 19

Slide 19 text

protected function createResponse( GuzzleResponse $gResponse, Request $request ) { $response = new Response( $gResponse->getBody(), $gResponse->getStatusCode() ); foreach ($gResponse->getHeaderLines() as $header) { list($name, $value) = explode(':', $header, 2); $response->headers->set($name, $value); } return $this->prepareResponse($response, $request); } nousefreak/proxy  

Slide 20

Slide 20 text

Yaml

Slide 21

Slide 21 text

use Symfony\Component\Yaml\Yaml; $yaml = << array( // 'username' => 'kuba', // 'password' => '123123' // ) // )

Slide 22

Slide 22 text

foo: &foo bar: ~ hello: cześć test: <<: *foo bar: true obj: !!php/object:O:8:"stdClass":1:{s: 5:"title";s:14:"Foo in the bar";}

Slide 23

Slide 23 text

in the wild…

Slide 24

Slide 24 text

namespace Nelmio\Alice\Loader; use Symfony\Component\Yaml\Yaml as YamlParser; class Yaml extends Base { public function load($file) { ob_start(); $loader = $this; $includeWrapper = function () use ($file, $loader) { return include $file; }; $data = $includeWrapper(); if (true !== $data) { $yaml = ob_get_clean(); $data = YamlParser::parse($yaml); } // ... } } nelmio/alice  

Slide 25

Slide 25 text

Debug

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

\Symfony\Component\Debug\Debug::enable();

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

No content

Slide 31

Slide 31 text

in the wild…

Slide 32

Slide 32 text

#!/usr/bin/env php run(); carew/carew  

Slide 33

Slide 33 text

Hiding dirty details

Slide 34

Slide 34 text

Process

Slide 35

Slide 35 text

use Symfony\Component\Process\Process; $process = new Process('ls –l'); $exitCode = $process->run(); $output = $process->getOutput();

Slide 36

Slide 36 text

$process = new PhpProcess( 'run(); $output = $process->getOutput();

Slide 37

Slide 37 text

$printCallback = function ($type, $data) { printf('[%s] %s', $type, $data); }; $process = new Process( 'echo "Symfony"; sleep 2; echo "Con";' ); $process->start($printCallback); // [...] do other stuff while command is running $pid = $process->getPid(); // wait untill it finishes $process->wait();

Slide 38

Slide 38 text

in the wild…

Slide 39

Slide 39 text

$server = new HttpServer\HttpServer( '/var/www', 'localhost', 8080 ); $server->start(); $contents = file_get_contents( 'http://localhost:8080/example.php' ); $server->stop(); robloach/h6pserver  

Slide 40

Slide 40 text

class HttpServer extends PhpProcess { // ... public function start($callback = null) { if (false === $php = $this->executableFinder->find()) { throw new \RuntimeException('Unable to find PHP'); } $options = ' -S ' . $this->addr . ':' . $this->port; if (isset($this->documentRoot)) { $options .= ' -t ' . $this->documentRoot; } $this->setCommandLine($php . $options); parent::start($callback); } } robloach/h6pserver  

Slide 41

Slide 41 text

Making better developers

Slide 42

Slide 42 text

EventDispatcher

Slide 43

Slide 43 text

Subjects   Listeners   Event  Dispatcher   Mailer  Listener   RegistraAon   Dispatcher   add  listener   registraAon.success   noAfy   registraAon.success   call   register  

Slide 44

Slide 44 text

Subjects   Listeners   Event  Dispatcher   Mailer   Listener   RegistraAon   Dispatcher   add  listener   registraAon.success   noAfy   registraAon.success   call   SMS   Listener   add  listener   registraAon.success   call   register  

Slide 45

Slide 45 text

use Symfony\Component\EventDispatcher\EventDispatcherInterface; class Registration { private $dispatcher; public function __construct( EventDispatcherInterface $dispatcher ) { $this->dispatcher = $dispatcher; } // ... }

Slide 46

Slide 46 text

use Symfony\Component\EventDispatcher\GenericEvent; class Registration { // ... public function register($user) { // register the user ... // dispatch an event if registration was // successful $this->dispatcher->dispatch( 'registration.success', new GenericEvent($user) ); } }

Slide 47

Slide 47 text

class MailerListener { private $mailer; private $twig; public function __construct( Mailer $mailer, TwigEngine $twig ) { $this->mailer = $mailer; $this->twig = $twig; } // ... }

Slide 48

Slide 48 text

use Symfony\Component\EventDispatcher\GenericEvent; class MailerListener { // ... public function sendMail(GenericEvent $event) { $user = $event->getSubject(); $message = $this->createMessage($user) $this->mailer->send($message); } private function createMessage($user) { return $this->twig->render(/* */); } }

Slide 49

Slide 49 text

use Symfony\Component\EventDispatcher\EventDispatcher; $mailerListener = new MailerListener($mailer, $twig); $smsListener = new SmsListener($smsGateway); $dispatcher = new EventDispatcher(); $dispatcher->addListener( 'registration.success', array($mailerListener, 'sendMail') ); $dispatcher->addListener( 'registration.success', array($smsListener, 'sendSms’) ); $registration = new Registration($dispatcher); $registration->register($user);

Slide 50

Slide 50 text

in the wild…

Slide 51

Slide 51 text

use Phoebe\Connection; use Phoebe\Event\Event; $freenode = new Connection(); $freenode->setServerHostname('irc.freenode.net'); $freenode->setNickname('Phoebe2'); $dispatcher = $freenode->getEventDispatcher(); $dispatcher->addListener( 'irc.received.001', function (Event $event) { $event->getWriteStream()->ircJoin('#symfony'); } ); $events->addSubscriber(new BeerPlugin()); sAl/phoebe  

Slide 52

Slide 52 text

use Phoebe\Event\Event; use Phoebe\Plugin\PluginInterface; class BeerPlugin implements PluginInterface { public static function getSubscribedEvents() { return [ 'irc.received.PRIVMSG' => array('onMessage', 0) ]; } public function onMessage(Event $event) { $message = $event->getMessage(); if (!$message->matchText('/SymfonyCon/') { return; } $es = $event->getWriteStream(); $es->ircPrivmsg($message->getSource(), 'Hello!'); } } sAl/phoebe  

Slide 53

Slide 53 text

https://github.com/jakzal/SymfonyConBot sAl/phoebe  

Slide 54

Slide 54 text

DependencyInjection

Slide 55

Slide 55 text

class appDevDebugProjectContainer extends Container { protected function getSymfonyConApiService() { $this->services['symfonycon.api'] = $instance = new SymfonyConApi(); return $instance; } }

Slide 56

Slide 56 text

Slide 57

Slide 57 text

%symfonycon.api.username% %symfonycon.api.key% %symfonycon.api.endpoint%

Slide 58

Slide 58 text

in the wild…

Slide 59

Slide 59 text

// BehatApplication protected function createContainer( InputInterface $input ) { $container = new ContainerBuilder(); $this->loadCoreExtension( $container, $this->loadConfiguration( $container, $input ) ); $container->compile(); return $container; } behat/behat  

Slide 60

Slide 60 text

default: extensions: Behat\Symfony2Extension\Extension: mink_driver: true Behat\MinkExtension\Extension: default_session: symfony2 PSS\Behat\Symfony2MockerExtension\Extension: ~ behat/behat  

Slide 61

Slide 61 text

namespace PSS\Behat\Symfony2MockerExtension; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Behat\Behat\Extension\ExtensionInterface; class Extension implements ExtensionInterface { public function load( array $config, ContainerBuilder $container ) { $loader = new XmlFileLoader( $container, new FileLocator(__DIR__.'/services') ); $loader->load('core.xml'); } // ... } behat/behat  

Slide 62

Slide 62 text

Having healthy relationships

Slide 63

Slide 63 text

Routing

Slide 64

Slide 64 text

use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Route; $routes = new RouteCollection(); $routes->add( 'hello', new Route( '/hello/{name}', array('controller' => 'HelloController') ) );

Slide 65

Slide 65 text

use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; $context = new RequestContext( '/hello/Poland', 'GET’ ); $matcher = new UrlMatcher($routes, $context); $parameters = $matcher->match('/hello/Poland'); var_dump($parameters); // array( // 'controller' => 'HelloController', // 'name' => 'Poland', // '_route' => 'hello' // )

Slide 66

Slide 66 text

use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; $request = Request::createFromGlobals(); $context = new RequestContext(); $context->fromRequest($request); $matcher = new UrlMatcher($routes, $context);

Slide 67

Slide 67 text

in the wild…

Slide 68

Slide 68 text

use Ratchet\App; use Ratchet\Server\EchoServer; $app = new App('localhost', 8080); $app->route('/chat', new MyChat()); $app->route('/echo', new EchoServer(), ['*']); $app->run(); cboden/ratchet  

Slide 69

Slide 69 text

Leading innovation

Slide 70

Slide 70 text

ExpressionLanguage

Slide 71

Slide 71 text

use Symfony\Component\ExpressionLanguage\ExpressionLanguage; $language = new ExpressionLanguage(); echo $language->evaluate('1 + 1'); // 2 echo $language->compile('1 + 2'); // (1 + 2)

Slide 72

Slide 72 text

echo $language->evaluate( 'life + universe + everything', array( 'life' => 10, 'universe' => 10, 'everything' => 22, ) ); // 42

Slide 73

Slide 73 text

class Conference { public function getName() { return 'SymfonyCon'; } } echo $language->evaluate( 'c.getName()', array('c' => new Conference('SymfonyCon')) ); // SymfonyCon

Slide 74

Slide 74 text

$language->register( 'reverse', function ($string) { if (!is_string($string)) { return $string; } return sprintf('strrev(%s)', $string); }, function ($arguments, $string) { if (!is_string($string)) { return $string; } return strrev($string); } ); echo $language->evaluate('reverse("SymfonyCon")');

Slide 75

Slide 75 text

services: symfonycon.api: class: SymfonyCon\Api arguments: - "@=service('factory').getHttpClient()" new \SymfonyCon\Api( $container->get('factory')->getHttpClient() );

Slide 76

Slide 76 text

"@=container.hasParameter('a') ? parameter('a') : 'default'"

Slide 77

Slide 77 text

/** * @Route("/post/{id}") * @Cache(lastModified="post.getUpdatedAt()") */ public function showAction(Post $post) { }

Slide 78

Slide 78 text

/** * @Route("/post/{id}") * @Method("GET") * @Cache(lastModified="post.getUpdatedAt()") * @ParamConverter("post", class="Sensio:Post") * @Security("has_role('ROLE_USER')") * @Template() * @MyResponseConverter("xml") */ public function showAction(Post $post) { return $post; } Annotation Driven Development

Slide 79

Slide 79 text

in the wild…

Slide 80

Slide 80 text

/** * @Hateoas\Relation( * "self", * href = "expr('/api/users/' ~ object.getId())" * ) */ class Post {} willdurand/hateoas  

Slide 81

Slide 81 text

use BCC\EnumerableUtility\Collection; $values = new Collection(array(1, 2, 3)); $values->where(function($item) { return $item % 2; }); $values->select(array( 'i' => 'i * m', 'm' => 2, )); bcc/enumerable-­‐uAlity  

Slide 82

Slide 82 text

It’s Plug & Play!

Slide 83

Slide 83 text

Console DomCrawler CssSelector

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

No content

Slide 86

Slide 86 text

No content

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

No content

Slide 94

Slide 94 text

Symfony Components •  Make PHP better •  Make your code better •  Make you better

Slide 95

Slide 95 text

Thank you! o  I work @SensioLabsUK o  I tweet @jakub_zalas o  I code @jakzal

Slide 96

Slide 96 text

Credits •  http://www.sxc.hu/photo/1223174 •  http://www.sxc.hu/photo/338038 •  http://www.sxc.hu/photo/13223 •  http://www.sxc.hu/photo/1092493 •  http://www.sxc.hu/photo/308460 •  http://www.sxc.hu/photo/1412072 •  http://www.sxc.hu/photo/771223 •  http://www.sxc.hu/photo/1178514 •  http://www.sxc.hu/photo/1379212 •  http://www.sxc.hu/photo/1432060 •  http://www.sxc.hu/photo/1115716