Symfonycomponents in     the wild	   Jakub Zalas
Who am I?	o  Remembers symfony 1.0   (2007)	o  Open Source contributor	o  BDD advocate	o  Works at Sensio Labs UK	o  ZCE &...
What is Symfony?	                                  First, Symfony2 is a reusable set 	                            of stand...
Why does it matter?	                           * 76% of statistics found on the Internet is made uphttp://www.sxc.hu/photo...
Reinventing the wheel	http://flic.kr/p/Mu9m2
Maintenance hell	http://www.sxc.hu/photo/1005333
Symfony components	   HttpFoundation	                                 Console	              Validator	        Form	   Rout...
HttpFoundation	http://www.sxc.hu/photo/1212545
use SymfonyComponentHttpFoundationRequest;	use SymfonyComponentHttpFoundationResponse;		$request = Request::createFromGlob...
use SymfonyComponentHttpFoundationRequest;	use SymfonyComponentHttpFoundationResponse;		$request = Request::createFromGlob...
$request = Request::createFromGlobals();	$session = $request->getSession();	if ($session->has(referrer)) {	    $referrer =...
$request = Request::createFromGlobals();	$date = getPageUpdatedAtById($request->query->get(id));	$response = new Response(...
How to check if a request is made over ssl?	•  is there HTTPS in the server vars? is it on or 1?	•  or is there SSL_HTTPS ...
Routing	http://www.sxc.hu/photo/1070609
use SymfonyComponentRoutingRouteCollection;	use SymfonyComponentRoutingRoute;	$routes = new RouteCollection();	$routes->ad...
use SymfonyComponentRoutingMatcherUrlMatcher;	use SymfonyComponentRoutingRequestContext;	$matcher = new UrlMatcher($routes...
use SymfonyComponentRoutingMatcherUrlMatcher;	use SymfonyComponentRoutingRequestContext;	$matcher = new UrlMatcher($routes...
use SymfonyComponentRoutingMatcherUrlMatcher;	use SymfonyComponentRoutingRequestContext;	  $routes->add(hello, new Route(/...
$routes = new RouteCollection();	$routes->add(hello, new Route(	      /hello/{name},	      array(controller => HelloContro...
use SymfonyComponentRoutingException;	$routes = new RouteCollection();	$routes->add(hello, new Route(	      /hello/{name},...
use SymfonyComponentRoutingGeneratorUrlGenerator;	$generator = new UrlGenerator(	     $routes, new RequestContext()	);	// ...
EventDispatcher	http://www.sxc.hu/photo/715294
use SymfonyComponentEventDispatcherEventDispatcher;	use SymfonyComponentEventDispatcherEvent;	$dispatcher = new EventDispa...
printf("Hello!n");	$dispatcher->dispatch(received_hello, new Event());	               Hello!	               Hello from lis...
$dispatcher = new EventDispatcher();	$dispatcher->addListener(	     received_hello,	     function (Event $event) {	       ...
printf("Hello!n");	$dispatcher->dispatch(received_hello, new Event());	               Hello!	               Hello from lis...
$dispatcher = new EventDispatcher();	$dispatcher->addListener(	    received_hello,	    function (Event $event) {	        p...
printf("Hello!n");	$dispatcher->dispatch(received_hello, new Event());	               Hello!	               Hello from lis...
$app = new SilexApplication();	$app->after(	     function (Request $request, Response $response) {	         // http://phpn...
// Silex/src/Silex/Application.php:304	public function after($callback, $priority = 0)	{	    $this[dispatcher]->addListene...
// Silex/src/Silex/Application.php:603	$this[dispatcher]->dispatch(SilexEvents::AFTER, $event);
HttpKernel	http://www.sxc.hu/photo/835732
$resolver = new ControllerResolver();	$httpKernel = new HttpKernel($dispatcher, $resolver);	$request = Request::create(/he...
$matcher = new UrlMatcher($routes, new RequestContext());	$dispatcher = new EventDispatcher();	$dispatcher->addListener(	 ...
use SymfonyComponentRoutingRouteCollection;	use SymfonyComponentRoutingRoute;	$routes = new RouteCollection();	$routes->ad...
use SymfonyComponentHttpFoundationRequest;	use SymfonyComponentHttpFoundationResponse;	class PhpnwController	{	    public ...
$response = $httpKernel->handle(Request::create(/bye));	PHP Fatal error: Uncaught exception SymfonyComponentRoutingExcepti...
$dispatcher->addListener(	     KernelEvents::EXCEPTION, 	     function (GetResponseForExceptionEvent $event) {	          $...
Console	http://www.sxc.hu/photo/910912
use SymfonyComponentConsoleCommandCommand;	use SymfonyComponentConsoleInputInputInterface;	use SymfonyComponentConsoleOutp...
public function configure()	{	    $this->setDescription(Outputs welcome message[...]);	    $this->setHelp(Outputs welcome ...
$application = new Application(Demo, 1.0.0);	$application->add(new HelloCommand(hello));	$application->run();
protected function execute(InputInterface $input, 	    OutputInterface $output)	{	          $name = $input->getArgument(na...
public function configure()	{	    // [...]	      $this->addOption(	           more, 	           m, 	           InputOption...
protected function execute(InputInterface $input, 	    OutputInterface $output)	{	          $name = $input->getArgument(na...
How to start?	   // composer.json	   {	             "require": {	                       "symfony/http-foundation": "2.1.2"...
Why Symfony?	 •  Good code covered by tests	 •  Flexible	 •  Secure	 •  Stable API (@api annotation)	 •  Long term support...
Thank you!	                                          Rate my talk:	                                       https://joind.in...
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
Upcoming SlideShare
Loading in...5
×

Symfony components in the wild, PHPNW12

2,352

Published on

Symfony is a set of reusable and decoupled PHP components designed to solve common web development problems. While as a framework it might not be the best for some of your projects, you can always build on top of its solid foundation of well written, tested and flexible components.

Original presentation: https://docs.google.com/presentation/pub?id=136blt1DWJ95yuEdpmjz9dIqgg38VwEXBQlY7bu0Op8w&start=false&loop=false&delayms=3000

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,352
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
18
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Symfony components in the wild, PHPNW12

  1. 1. Symfonycomponents in the wild Jakub Zalas
  2. 2. Who am I? o  Remembers symfony 1.0 (2007) o  Open Source contributor o  BDD advocate o  Works at Sensio Labs UK o  ZCE & Sensio Labs o  Twitter: @jakub_zalas Certi"ed Symfony o  Blog: http://zalas.eu Developer o  Github: @jakzal
  3. 3. What is Symfony? First, Symfony2 is a reusable set of standalone, decoupled, and cohesive PHP components that solve common web development problems. Then, based on these components, Symfony2 is also a full-stack web framework. http://www.sxc.hu/photo/1197009 http://fabien.potencier.org/article/49/what-is-symfony2
  4. 4. Why does it matter? * 76% of statistics found on the Internet is made uphttp://www.sxc.hu/photo/1223174
  5. 5. Reinventing the wheel http://flic.kr/p/Mu9m2
  6. 6. Maintenance hell http://www.sxc.hu/photo/1005333
  7. 7. Symfony components HttpFoundation Console Validator Form Routing HttpKernel OptionsResolver CssSelector DependencyInjection BrowserKit DomCrawler Translation EventDispatcher Security Locale Templating Filesystem Con"g Process Finder ClassLoader Yaml Serializer http://www.sxc.hu/photo/338038
  8. 8. HttpFoundation http://www.sxc.hu/photo/1212545
  9. 9. use SymfonyComponentHttpFoundationRequest; use SymfonyComponentHttpFoundationResponse; $request = Request::createFromGlobals(); $name = $request->query->get(name, PHPNW); $message = "Hello $name!"; $response = new Response($message, 200); $response->headers->set(X-REQUEST-NAME, $name); $response->headers->setCookie(new Cookie(phpnw, $name)); $response->send();
  10. 10. use SymfonyComponentHttpFoundationRequest; use SymfonyComponentHttpFoundationResponse; $request = Request::createFromGlobals(); $name = $request->query->get(name, PHPNW); $message = "Hello $name!"; $request->request $response = new Response($message, 200); $request->query $response->headers->set(X-REQUEST-NAME, $name); $request->server $response->headers->setCookie(new Cookie(phpnw, $name)); $request->files $response->send(); $request->cookies $request->headers $request->attributes
  11. 11. $request = Request::createFromGlobals(); $session = $request->getSession(); if ($session->has(referrer)) { $referrer = $session->get(referrer); return new RedirectResponse($referrer); } if ($session->hasFlash(notice)) { return new Response($session->getFlash(notice)); } else { $session->setFlash(notice, Hello again!); return new Response(Foo) }
  12. 12. $request = Request::createFromGlobals(); $date = getPageUpdatedAtById($request->query->get(id)); $response = new Response(); $response->setPublic(); $response->setLastModified($date); if ($response->isNotModified($request)) { return $response; } // else do heavy processing to render the page
  13. 13. How to check if a request is made over ssl? •  is there HTTPS in the server vars? is it on or 1? •  or is there SSL_HTTPS header? is it on or 1? •  or is there X_FORWARDED_PROTO header set to https if ($request->isSecure()) { // were fine}
  14. 14. Routing http://www.sxc.hu/photo/1070609
  15. 15. use SymfonyComponentRoutingRouteCollection; use SymfonyComponentRoutingRoute; $routes = new RouteCollection(); $routes->add(hello, new Route(/hello/{name}, array( controller => HelloController ))); $routes->add(homepage, new Route(/, array( controller => HomepageController )));
  16. 16. use SymfonyComponentRoutingMatcherUrlMatcher; use SymfonyComponentRoutingRequestContext; $matcher = new UrlMatcher($routes, new RequestContext()); $parameters = $matcher->match(/); var_dump($parameters); // array( // controller => HomepageController, // _route => homepage // )
  17. 17. use SymfonyComponentRoutingMatcherUrlMatcher; use SymfonyComponentRoutingRequestContext; $matcher = new UrlMatcher($routes, new RequestContext()); $parameters = $matcher->match(/hello/PHPNW); var_dump($parameters); // array( // controller => HelloController, // name => PHPNW, // _route => hello // )
  18. 18. use SymfonyComponentRoutingMatcherUrlMatcher; use SymfonyComponentRoutingRequestContext; $routes->add(hello, new Route(/hello/{name}, array( $matcher = new UrlMatcher($routes, new RequestContext()); controller => HelloController ))); $parameters = $matcher->match(/hello/PHPNW); var_dump($parameters); // array( // controller => HelloController, // name => PHPNW, // _route => hello // )
  19. 19. $routes = new RouteCollection(); $routes->add(hello, new Route( /hello/{name}, array(controller => HelloController), array(name => ^[a-zA-Z]+$) )); $matcher = new UrlMatcher($routes, new RequestContext()); $parameters = $matcher->match(/hello/PHPNW); var_dump($parameters); // array( // controller => HelloController, // name => PHPNW, // _route => hello // )
  20. 20. use SymfonyComponentRoutingException; $routes = new RouteCollection(); $routes->add(hello, new Route( /hello/{name}, array(controller => HelloController), array(name => ^[a-zA-Z]+$) )); $matcher = new UrlMatcher($routes, new RequestContext()); try { $matcher->match(/hello/PHPNW12); } catch (ExceptionResourceNotFoundException $exception) { die(Resource not found); }
  21. 21. use SymfonyComponentRoutingGeneratorUrlGenerator; $generator = new UrlGenerator( $routes, new RequestContext() ); // "/hello/PHPNW" $url = $generator->generate( hello, array(name => PHPNW) ); // "http://localhost/hello/PHPNW" $url = $generator->generate( hello, array(name => PHPNW), true );
  22. 22. EventDispatcher http://www.sxc.hu/photo/715294
  23. 23. use SymfonyComponentEventDispatcherEventDispatcher; use SymfonyComponentEventDispatcherEvent; $dispatcher = new EventDispatcher(); $dispatcher->addListener( received_hello, function (Event $event) { printf("Hello from listener 1!n"); } ); $dispatcher->addListener( received_hello, function (Event $event) { printf("Hello from listener 2!n"); } );
  24. 24. printf("Hello!n"); $dispatcher->dispatch(received_hello, new Event()); Hello! Hello from listener 1! Hello from listener 2!
  25. 25. $dispatcher = new EventDispatcher(); $dispatcher->addListener( received_hello, function (Event $event) { printf("Hello from listener 1!n"); }, 0 ); $dispatcher->addListener( received_hello, function (Event $event) { printf("Hello from listener 2!n"); }, 10 );
  26. 26. printf("Hello!n"); $dispatcher->dispatch(received_hello, new Event()); Hello! Hello from listener 2! Hello from listener 1!
  27. 27. $dispatcher = new EventDispatcher(); $dispatcher->addListener( received_hello, function (Event $event) { printf("Hello from listener 1!n"); $event->stopPropagation(); } ); $dispatcher->addListener( received_hello, function (Event $event) { printf("Hello from listener 2!n"); } );
  28. 28. printf("Hello!n"); $dispatcher->dispatch(received_hello, new Event()); Hello! Hello from listener 1!
  29. 29. $app = new SilexApplication(); $app->after( function (Request $request, Response $response) { // http://phpnw.dev/?hello=1 if ($request->query->get(hello) === 1) { $content = str_replace( </body>, Hello!!</body>, $response->getContent() ); $response->setContent($content); } } );
  30. 30. // Silex/src/Silex/Application.php:304 public function after($callback, $priority = 0) { $this[dispatcher]->addListener( SilexEvents::AFTER, function (FilterResponseEvent $event) use ($callback) { call_user_func( $callback, $event->getRequest(), $event->getResponse() ); }, $priority ); }
  31. 31. // Silex/src/Silex/Application.php:603 $this[dispatcher]->dispatch(SilexEvents::AFTER, $event);
  32. 32. HttpKernel http://www.sxc.hu/photo/835732
  33. 33. $resolver = new ControllerResolver(); $httpKernel = new HttpKernel($dispatcher, $resolver); $request = Request::create(/hello/PHPNW) $response = $httpKernel->handle($request); echo $response; HTTP/1.0 200 OK Cache-Control: no-cache Date: Sat, 06 Oct 2012 14:32:14 GMT Hello PHPNW
  34. 34. $matcher = new UrlMatcher($routes, new RequestContext()); $dispatcher = new EventDispatcher(); $dispatcher->addListener( KernelEvents::REQUEST, function (GetResponseEvent $event) use ($matcher) { $request = $event->getRequest(); $pathInfo = $request->getPathInfo(); // array contains _controler, name, _route $parameters = $matcher->match($pathInfo); $request->attributes->add($parameters); } );
  35. 35. use SymfonyComponentRoutingRouteCollection; use SymfonyComponentRoutingRoute; $routes = new RouteCollection(); $routes->add(hello, new Route(/hello/{name}, array( _controller => PhpnwController::hello ))); $routes->add(homepage, new Route(/, array( _controller => PhpnwController::homepage )));
  36. 36. use SymfonyComponentHttpFoundationRequest; use SymfonyComponentHttpFoundationResponse; class PhpnwController { public function hello(Request $request, $name) { return new Response(Hello .$name.PHP_EOL); } public function homepage(Request $request) { return new Response(Home sweet home.PHP_EOL); } }
  37. 37. $response = $httpKernel->handle(Request::create(/bye)); PHP Fatal error: Uncaught exception SymfonyComponentRoutingExceptionResourceNotFoundException in /home/vagrant/Projects/WildComponents/vendor/symfony/routing/Symfony/Component/Routing/Matcher/UrlMatcher.php:81
  38. 38. $dispatcher->addListener( KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) { $message = $event->getException()->getMessage(); $response = new Response($message, 404); $event->setResponse($response); } ); HTTP/1.0 404 Not Found Cache-Control: no-cache Date: Sat, 06 Oct 2012 09:01:02 GMT Unable to find the controller for path "/bye". Maybe you forgot to add the matching route in your routing configuration?
  39. 39. Console http://www.sxc.hu/photo/910912
  40. 40. use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputInterface; use SymfonyComponentConsoleOutputOutputInterface; class HelloCommand extends Command { public function configure() { // configure the command [...] } protected function execute(InputInterface $input, OutputInterface $output) { // put your code here [...] } }
  41. 41. public function configure() { $this->setDescription(Outputs welcome message[...]); $this->setHelp(Outputs welcome message.); $this->addArgument( name, InputArgument::OPTIONAL, The name to output to the screen, World ); }
  42. 42. $application = new Application(Demo, 1.0.0); $application->add(new HelloCommand(hello)); $application->run();
  43. 43. protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument(name); $output->writeln(sprintf(Hello %s!, $name)); } }
  44. 44. public function configure() { // [...] $this->addOption( more, m, InputOption::VALUE_NONE, Tell me more ); }
  45. 45. protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument(name); $output->writeln(sprintf(Hello %s!, $name)); if ($input->getOption(more)) { $output->writeln(It is really nice to meet you!); } } }
  46. 46. How to start? // composer.json { "require": { "symfony/http-foundation": "2.1.2" } } curl -s https://getcomposer.org/installer | php php composer.phar install http://www.sxc.hu/photo/1092493
  47. 47. Why Symfony? •  Good code covered by tests •  Flexible •  Secure •  Stable API (@api annotation) •  Long term support •  Outstanding community •  Wide adoption
  48. 48. Thank you! Rate my talk: https://joind.in/6945 Interested in training? Were introducing Symfony Components trainings soon: http://www.sensiolabs.co.uk/training/symfony2.html
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×