SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
Introducing




Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




          Allow me to introduce myself
                                              Claudio Beatrice                  6+ years of
                                                @omissis                     experience on PHP

                                            Organizing Drupal
                                            events since 2009


                                               PHP, Drupal &
                                             Symfony consulting




                                                   Web Radio                   Telecommunications


                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                             What’s Symfony2
                        A reusable set of standalone, decoupled,
                        and cohesive PHP 5.3 components


                                                                A full-stack web framework


                        A Request/Response framework built
                        around the HTTP specification

                                                         A promoter of best practices,
                                                    standardization and interoperability

                        An awesome community!

                                                                                         © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




             Leave The STUPID Alone
    As time went by, habits and practices that once seemed
    acceptable have proven that they were making our code
    harder to understand and maintain. In other words, STUPID.
    But what makes code such a thing?
    •   Singleton
    •   Tight coupling
    •   Untestability
    •   Premature optimization
    •   Indescriptive naming
    •   Duplication

                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                  Singleton
    It’s a design pattern that restricts the creation of an object
    to one instance(think of a DB connection).

    It does introduce undesirable limitations(what if we’ll need
    TWO DB connections?), global state and hardcoded
    dependencies which are all making code more difficult to
    test and more coupled.




                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                      Singleton
                        class DB
                        {
                            private static $instance;

                            private function __construct()
                            {
                                // ... code goes here ...
                            }

                            public static function getInstance()
                            {
                                if (empty(self::$instance)) {
                                    self::$instance = new self;
                                }
                                return self::$instance;
                            }

                                // ... more code goes here ...
                        }


                                                                                     © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Tight Coupling
    It happens when classes are put in relation by using type
    hints, static calls or direct instantiation.

                                                       Introduces hardcoded
                                                       dependencies between
                                                       classes, which complicates:
                                                       •   code reuse
                                                       •   unit testing
                                                       •   integration
                                                       •   modifications


                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                             Tight Coupling
                   // An example of tight coupling
                   class House {
                       public function __construct() {
                           $this->door   = new Door();
                           $this->window = new Window();
                       }
                   }

                   // And a possible solution
                   class House {
                       // Door and Window are interfaces
                       public function __construct(Door $door, Window $window) {
                           $this->door   = $door;
                           $this->window = $window;
                       }
                   }




                                                                                      © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                            Untestability

    If classes are complex, tightly coupled or trying to do too
    much, then there’s a good chance that it’s also quite hard if
    not impossible to test it in isolation.


    The lack of proper test coverage will make code harder to
    maintain and change, as it becomes very difficult to tell if
    any modification is actually breaking something.



                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                 Premature Optimization
     Most of the time major
     performance issues are
     caused by small portions
     of code(80/20 rule).
     It is easier to optimize
     correct code than to
     correct optimized code.

      Performance are not always a concern, therefore
      optimize when it’s a proved problem, you’ll save time
      and raise productivity.

                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Indescriptive Naming
                   There are two hard things in computer science:
           cache invalidation, naming things and off-by-one errors.
                                      -- Phil Karlton, variated by the Interwebs




    Even if hard, naming is a fundamental part of the job and
    should be considered part of the documentation, therefore
    remember to:
    • communicate intents
    • favor clarity over brevity
    • think that code is read far more often than written, so
      it’s more convenient to ease “reads” over “writes”

                                                                                     © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                              Duplication
       How many times did they tell you to not repeat yourself?




                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                BE SOLID!
    What alternatives to write STUPID code do we have?
    Another acronym to the rescue: SOLID!
    It encloses five class design principles:
    •   Single responsibility principle
    •   Open/closed principle
    •   Liskov substitution principle
    •   Interface segregation principle
    •   Dependency inversion principle




                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Single Responsibility
                          There should never be more than
                          one reason for a class to change.


        Every class should have a single responsibility and fully
        encapsulate it.
        If change becomes localized, complexity and cost of
        change are reduced, moreover there’s less risk of ripple
        effects.



                                                                                    © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Single Responsibility
                                interface Modem
                                {
                                    function dial($phoneNumber);
                                    function hangup();
                                    function send($message);
                                    function receive();
                                }




    The above interface shows two responsibilities: connection
    management and data communication, making them good
    candidates for two separate interfaces/implementations.


                                                                                    © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                              Open/Closed
                   Software entities (classes, functions, etc) should
                   be open for extension, but closed for modification.
         This principle states that the source code of software
         entities shouldn’t ever be changed: those entities must be
         derived in order to add the wanted behaviors.

                                                                                          Abstract
           Client             Server                               Client
                                                                                           Server


                                                                                           Server

                                                                                    © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Liskov Substitution
        Objects in a program should be replaceable with
        instances of their subtypes without altering any of the
        desirable properties of that program, such as correctness
        and performed task.

        It intends to guarantee semantic interoperability of object
        types in a hierarchy.




                                                                                   © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                         Liskov Substitution
 class Rectangle {
   protected $width;
   protected $height;

   function             setWidth($width) {...}              function draw(Rectangle $r) {
   function             getWidth() {...}                      $r->setWidth(5);
   function             setHeight($height) {...}              $r->setHeight(4);
   function             getHeight() {...}
 }                                                            // is it correct to assume that
                                                            changing the width of a Rectangle
 class Square extends Rectangle {                           leaves is height unchanged?
   function setWidth($width) {                                assertEquals(
     $this->width = $width;                                      20,
     $this->height = $width;                                     $r->setWidth() * $r->setHeight()
   }                                                          );
   function setHeight($height) {                            }
     $this->width= $height;
     $this->height = $height;
   }
 }


                                                                                         © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Liskov Substitution

        The flaw in the Rectangle-Square design shows that even
        if conceptually a square is a rectangle, a Square object is
        not a Rectangle object, since a Square does not behave
        as a Rectangle.
        As a result, the public behavior the clients expect for the
        base class must be preserved in order to conform to the
        LSP.



                                                                                   © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Interface Segregation
       Many client-specific interfaces are better than one big one.
       This principle helps decreasing the coupling between
       objects by minimizing the intersecting surface.
                                                             interface Printer
                                                             {
                                                                 function print(...);
                                                             }
        interface MultiFunctionPrinter
        {                                                    interface Scanner
            function print(...);                             {
            function scan(...);                                  function print(...);
            function fax(...);                               }
        }
                                                             interface Fax
                                                             {
                                                                 function print(...);
                                                             }

                                                                                    © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                    Dependency Inversion
    • High-level entities should not depend on low-level entities
      and both should depend on abstractions.
    • Abstractions should not depend upon details: details
      should depend upon abstractions.

                                  Component A
     Component A
                                    Service                     Component A Package



                                  Component B                   Component B Package

                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                    Dependency Inversion
                        class Vehicle {
                            protected $tyres;

                            public function __construct() {
                                $this->tyres = array_fill(0, 4, new Tyre(50));
                            }
                        }
                        class Tyre {
                            private $diameter;

                            public function __construct($diameter) {
                                $this->setDiameter($diameter);
                            }

                            public function setDiameter($diameter) {
                                $this->diameter = $diameter;
                            }

                            public function getDiameter() {
                                return $this->diameter;
                            }
                        }

                                                                                      © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                    Dependency Inversion
   namespace Vehicle;                                        namespace Vehicle;

   class Vehicle {                                           abstract class AbstractTyre {
       protected $tyres;                                         private $diameter;

       function addTyre(AbstractTyre $tyre) {                    function __construct($diameter) {...}
           $this->tyres[] = $tyre;
       }                                                         function setDiameter($diameter) {...}
   }
                                                                 function getDiameter() {...}
                                                             }


                                                        namespace Tyre;

                                                        use VehicleAbstractTyre;

                                                        class RaceTyre extends AbstractTyre {
                                                            private $compound;

                                                            function setCompound($compound) {...}

                                                            function getCompound() {...}
                                                        }

                                                                                    © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




        How About Symfony Now?
    Being aware of the principles of software development
    mentioned earlier allow us to better understand some of the
    choices that have been made for the framework as well as
    some of the tools that have been made available, such as:
    •   Class Loader
    •   Service Container
    •   Event Dispatcher
    •   HTTP Foundation
    •   HTTP Kernel



                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                       Class Loader
              It loads your project’s classes automatically if they’re
              following a standard PHP convention aka PSR-0.

                        • DoctrineCommonIsolatedClassLoader
                             => /path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php
                        • SymfonyCoreRequest
                             => /path/to/project/lib/vendor/Symfony/Core/Request.php
                        • Twig_Node_Expression_Array
                             => /path/to/project/lib/vendor/Twig/Node/Expression/Array.php




                        It’s a great way to get out of the require_once
                        hell while gaining better interoperability and
                        lazy loading at the same time.

                                                                                             © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Service Container
                               aka Dependency Injection Container

   A Service is any PHP object that
   performs a “global” task: think of a
   Mailer class.
   A Service Container is a special
   object (think of it as an Array of
   Objects on Steroids) that
   centralizes and standardizes the
   way objects are constructed inside an application: instead of
   directly creating Services, the developer configures the
   Container to take care of the task.

                                                                                  © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        Event Dispatcher
           A lightweight implementation of the Observer Pattern,
           it provides a powerful and easy way to extend objects.

                        Observer                                                  Observable
                        +update                                                    +attach
                                                                                   +detach
                                                                                   +notify


    ConcreteObserver1              ConcreteObserver2
                                                                             ConcreteObservable
              +update                  +update
                                                                                    +attach
                                                                                    +detach
                                                                                    +notify


                                                                                    © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                             Event Dispatcher

                        use SymfonyComponentEventDispatcherEventDispatcher;

                        $dispatcher = new EventDispatcher();

                        $callable = function (Event $event) use ($log) {
                            $log->addWarning(‘th3 n1nj4 d1sp4tch3r 1s 4ft3r y0u’);
                        }
                        $dispatcher->addListener(‘foo.bar’, $callable);

                        $dispatcher->dispatch(‘foo.bar’, new Event());




                                                                                         © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                          HTTP Foundation
      It replaces the PHP’s global variables and functions that
      represent either requests or responses with a full-featured
      object-oriented layer for the HTTP messages.
                   use SymfonyComponentHttpFoundationRequest;
                   // http://example.com/?foo=bar
                   $request = Request::createFromGlobals();
                   $request->query->get(‘foo’); // returns bar
                   // simulate a request
                   $request = Request::create('/foo', 'GET', array('name' => 'Bar'));


                   use SymfonyComponentHttpFoundationResponse;

                   $response = new Response('Content', 200, array(
                       'content-type' => 'text/html'
                   ));
                   // check the response is HTTP compliant and send it
                   $response->prepare($request);
                   $response->send();

                                                                                       © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                              HTTP Kernel
      The Kernel is the core of Symfony2: it is built on top of the
      HttpFoundation and its main goal is to “convert” a
      Request object into a Response object using a Controller,
      which in turn can be any kind of PHP callable.
             interface HttpKernelInterface
             {
                 const MASTER_REQUEST = 1;
                 const SUB_REQUEST = 2;

                 /**
                  * ...
                  * @return Response A Response instance
                  * ...
                  * @api
                  */
                 function handle(Request $request, $type = self::MASTER_REQUEST,
             $catch = true);
             }

                                                                                   © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                       HTTP Kernel
                                                      Workflow

                                                                                             exception

                              Sub-                  “sub-response” content
                             Request
                                                                                                  exception



                                     resolve                      resolve          call
    Request             request                   controller                    controller        response    Response
                                    controller                  arguments




                                                                                  view                        terminate




                                                                                              © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                  Symfony is not enough


                        Let’s take a look at some of the most
                        important third-party libraries




                                                                                   © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                  Doctrine2
       The Doctrine Project is made of a selected set of PHP
       libraries primarily focused on providing persistence
       services and related functionality:
       •   Common
       •   Database Abstraction Layer
       •   Object Relational Mapper
       •   MongoDB Object Document Mapper
       •   CouchDB Object Document Mapper
       •   PHPCR Object Document Mapper
       •   Migrations


                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                           Doctrine2
                        namespace DrupalBundleNodeBundleDocument;

                        use DoctrineODMMongoDBMappingAnnotations as MongoDB;
                        use DoctrineCommonPersistencePersistentObject;

                        /**
                          * @MongoDBDocument(collection="node")
                          */
                        class Node extends PersistentObject
                        {
                          /**
                             * @MongoDBId
                             */
                          protected $id;

                          /**
                           * @MongoDBString
                           */
                          protected $title;

                            // accessor and mutators
                        }

                                                                                          © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                            Twig
             A flexible, fast and secure template engine for PHP.
             It offers a great set of features, a concise syntax and
             very good performances (it compiles to PHP and
             has an optional C extension); moreover it’s super
             easy to extend and it’s thoughtfully documented.

             It gives the presentation layer a big boost
             in terms of expressiveness, making it
             more powerful and easier to use:
             prepare yourself for sweet hugs
             by front-end developers :)

                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                            Twig
      {# Node list page #}
      {% extends ‘layout.html.twig’ %}

      {% macro node_render(node) %}
          <div id=”node-{{node.id}}”>
              <h2>{{ node.title|title }}</h2>
              <div>{{ node.creationDate|date(‘d/m/Y’) }}</div>
              <div>{{ node.body }}</div>
              <div>{{ node.tags|join(‘, ‘) }}</div>
          </div>
      {% endmacro %}

      {% block body %}
          {% for node in nodes %}
              node_render(node);
          {% else %}
              {{ ‘We did not find any node.’|trans }}
          {% endfor %}
      {% endblock body %}




                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                                       Assetic
             An advanced asset management framework for PHP.
           $css = new AssetCollection(array(
               new FileAsset('/path/to/src/styles.less', array(new LessFilter())),
               new GlobAsset('/path/to/css/*'),
           ), array(
               new YuiCssCompressorFilter('/path/to/yuicompressor.jar'),
           ));

           // this will echo CSS compiled by LESS and compressed by YUI
           echo $css->dump();



             It ships with a strong set of filters for handling css, js,
             less, sass, compression, minifying and much more.
             Moreover, it’s nicely integrated with Twig.

                                                                                  © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




             Giving The Devil His Due
       Some resources I used to make these slides:
        •        http://nikic.github.com/
        •        http://fabien.potencier.org/
        •        http://symfony.com/
        •        http://www.slideshare.net/jwage/symfony2-from-the-trenches
        •        http://www.slideshare.net/weaverryan/handson-with-the-symfony2-framework
        •        http://www.slideshare.net/weaverryan/symony2-a-next-generation-php-framework
        •        http://martinfowler.com/articles/injection.html
        •        http://www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod




                                                                                            © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                        And Many Moar!




      Find many more Symfony2 Bundles and PHP Libraries at
      knpbundles.com and packagist.org! (and while you’re
      at it, take a look at Composer! ;)
                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12
Drupal Developer Days 2012 Barcelona - Introducing Symfony2




                              Thank You!
                                     Claudio Beatrice
                                        @omissis




                                                                                 © 2012 Agavee GmbH
Saturday, June 16, 12

Contenu connexe

En vedette

Leon product presentation
Leon product presentationLeon product presentation
Leon product presentationLisha Leon
 
Introducing SlideShare Business
Introducing SlideShare BusinessIntroducing SlideShare Business
Introducing SlideShare BusinessRashmi Sinha
 
Product Launching Presentation
Product Launching PresentationProduct Launching Presentation
Product Launching Presentationdianaists
 
Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codePaulo Gandra de Sousa
 
Introducing the new LinkedIn Sales Navigator
Introducing the new LinkedIn Sales NavigatorIntroducing the new LinkedIn Sales Navigator
Introducing the new LinkedIn Sales NavigatorLinkedIn Sales Solutions
 
SEOmoz Pitch Deck July 2011
SEOmoz Pitch Deck July 2011SEOmoz Pitch Deck July 2011
SEOmoz Pitch Deck July 2011Rand Fishkin
 

En vedette (9)

Leon product presentation
Leon product presentationLeon product presentation
Leon product presentation
 
Introducing SlideShare Business
Introducing SlideShare BusinessIntroducing SlideShare Business
Introducing SlideShare Business
 
Product Launching Presentation
Product Launching PresentationProduct Launching Presentation
Product Launching Presentation
 
Design Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID codeDesign Patterns: From STUPID to SOLID code
Design Patterns: From STUPID to SOLID code
 
Introducing Korea!
Introducing Korea!Introducing Korea!
Introducing Korea!
 
Anatomy of Seed
Anatomy of SeedAnatomy of Seed
Anatomy of Seed
 
Introducing the new LinkedIn Sales Navigator
Introducing the new LinkedIn Sales NavigatorIntroducing the new LinkedIn Sales Navigator
Introducing the new LinkedIn Sales Navigator
 
Slides That Rock
Slides That RockSlides That Rock
Slides That Rock
 
SEOmoz Pitch Deck July 2011
SEOmoz Pitch Deck July 2011SEOmoz Pitch Deck July 2011
SEOmoz Pitch Deck July 2011
 

Similaire à Introducing symfony2

9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot missMark Papis
 
Features java9
Features java9Features java9
Features java9srmohan06
 
Create a Symfony Application from a Drupal Perspective
Create a Symfony Application from a Drupal PerspectiveCreate a Symfony Application from a Drupal Perspective
Create a Symfony Application from a Drupal PerspectiveAcquia
 
Back-end with SonataAdminBundle (and Symfony2, of course...)
Back-end with SonataAdminBundle (and Symfony2, of course...)Back-end with SonataAdminBundle (and Symfony2, of course...)
Back-end with SonataAdminBundle (and Symfony2, of course...)Andrea Delfino
 
Cloud Foundry, the Open Platform as a Service - Oscon - July 2012
Cloud Foundry, the Open Platform as a Service - Oscon - July 2012Cloud Foundry, the Open Platform as a Service - Oscon - July 2012
Cloud Foundry, the Open Platform as a Service - Oscon - July 2012Patrick Chanezon
 
Automating Drupal Development with Patterns
Automating Drupal Development with PatternsAutomating Drupal Development with Patterns
Automating Drupal Development with PatternsDavid Rozas
 
Bridging the Gap Between Tablets and the LMS
Bridging the Gap Between Tablets and the LMSBridging the Gap Between Tablets and the LMS
Bridging the Gap Between Tablets and the LMSXyleme
 
What's Expected in Java 7
What's Expected in Java 7What's Expected in Java 7
What's Expected in Java 7Gal Marder
 
EdTechJoker Spring 2020 - Lecture 7 Drupal intro
EdTechJoker Spring 2020 - Lecture 7 Drupal introEdTechJoker Spring 2020 - Lecture 7 Drupal intro
EdTechJoker Spring 2020 - Lecture 7 Drupal introBryan Ollendyke
 
Modernisation of Legacy PHP Applications to Symfony2 - Symfony Live Berlin 2012
Modernisation of Legacy PHP Applications to Symfony2 - Symfony Live Berlin 2012Modernisation of Legacy PHP Applications to Symfony2 - Symfony Live Berlin 2012
Modernisation of Legacy PHP Applications to Symfony2 - Symfony Live Berlin 2012Fabrice Bernhard
 
Structuring your java application
Structuring your java applicationStructuring your java application
Structuring your java applicationwoody huang
 
Kubernetes - 7 lessons learned from 7 data centers in 7 months
Kubernetes - 7 lessons learned from 7 data centers in 7 monthsKubernetes - 7 lessons learned from 7 data centers in 7 months
Kubernetes - 7 lessons learned from 7 data centers in 7 monthsMichael Tougeron
 
Using OSGi as a Cloud Platform - Jan Rellermeyer
Using OSGi as a Cloud Platform - Jan RellermeyerUsing OSGi as a Cloud Platform - Jan Rellermeyer
Using OSGi as a Cloud Platform - Jan Rellermeyermfrancis
 
Bay Area Drupal Camp Efficiency
Bay Area Drupal Camp EfficiencyBay Area Drupal Camp Efficiency
Bay Area Drupal Camp Efficiencysmattoon
 
From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...Robert Munteanu
 
Symfony Day 2009 - Symfony vs Integrating products
Symfony Day 2009 - Symfony vs Integrating productsSymfony Day 2009 - Symfony vs Integrating products
Symfony Day 2009 - Symfony vs Integrating productsXavier Lacot
 
OSGi in Action Chapter 1 and 2
OSGi in Action Chapter 1 and 2OSGi in Action Chapter 1 and 2
OSGi in Action Chapter 1 and 2pjhInovex
 

Similaire à Introducing symfony2 (20)

9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss
 
Features java9
Features java9Features java9
Features java9
 
Create a Symfony Application from a Drupal Perspective
Create a Symfony Application from a Drupal PerspectiveCreate a Symfony Application from a Drupal Perspective
Create a Symfony Application from a Drupal Perspective
 
Back-end with SonataAdminBundle (and Symfony2, of course...)
Back-end with SonataAdminBundle (and Symfony2, of course...)Back-end with SonataAdminBundle (and Symfony2, of course...)
Back-end with SonataAdminBundle (and Symfony2, of course...)
 
Oops
OopsOops
Oops
 
Cloud foundry and openstackcloud
Cloud foundry and openstackcloudCloud foundry and openstackcloud
Cloud foundry and openstackcloud
 
Cloud Foundry, the Open Platform as a Service - Oscon - July 2012
Cloud Foundry, the Open Platform as a Service - Oscon - July 2012Cloud Foundry, the Open Platform as a Service - Oscon - July 2012
Cloud Foundry, the Open Platform as a Service - Oscon - July 2012
 
Automating Drupal Development with Patterns
Automating Drupal Development with PatternsAutomating Drupal Development with Patterns
Automating Drupal Development with Patterns
 
Bridging the Gap Between Tablets and the LMS
Bridging the Gap Between Tablets and the LMSBridging the Gap Between Tablets and the LMS
Bridging the Gap Between Tablets and the LMS
 
What's Expected in Java 7
What's Expected in Java 7What's Expected in Java 7
What's Expected in Java 7
 
EdTechJoker Spring 2020 - Lecture 7 Drupal intro
EdTechJoker Spring 2020 - Lecture 7 Drupal introEdTechJoker Spring 2020 - Lecture 7 Drupal intro
EdTechJoker Spring 2020 - Lecture 7 Drupal intro
 
Modernisation of Legacy PHP Applications to Symfony2 - Symfony Live Berlin 2012
Modernisation of Legacy PHP Applications to Symfony2 - Symfony Live Berlin 2012Modernisation of Legacy PHP Applications to Symfony2 - Symfony Live Berlin 2012
Modernisation of Legacy PHP Applications to Symfony2 - Symfony Live Berlin 2012
 
Structuring your java application
Structuring your java applicationStructuring your java application
Structuring your java application
 
Kubernetes - 7 lessons learned from 7 data centers in 7 months
Kubernetes - 7 lessons learned from 7 data centers in 7 monthsKubernetes - 7 lessons learned from 7 data centers in 7 months
Kubernetes - 7 lessons learned from 7 data centers in 7 months
 
Oop concepts
Oop conceptsOop concepts
Oop concepts
 
Using OSGi as a Cloud Platform - Jan Rellermeyer
Using OSGi as a Cloud Platform - Jan RellermeyerUsing OSGi as a Cloud Platform - Jan Rellermeyer
Using OSGi as a Cloud Platform - Jan Rellermeyer
 
Bay Area Drupal Camp Efficiency
Bay Area Drupal Camp EfficiencyBay Area Drupal Camp Efficiency
Bay Area Drupal Camp Efficiency
 
From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...
 
Symfony Day 2009 - Symfony vs Integrating products
Symfony Day 2009 - Symfony vs Integrating productsSymfony Day 2009 - Symfony vs Integrating products
Symfony Day 2009 - Symfony vs Integrating products
 
OSGi in Action Chapter 1 and 2
OSGi in Action Chapter 1 and 2OSGi in Action Chapter 1 and 2
OSGi in Action Chapter 1 and 2
 

Dernier

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 

Dernier (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 

Introducing symfony2

  • 2. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Allow me to introduce myself Claudio Beatrice 6+ years of @omissis experience on PHP Organizing Drupal events since 2009 PHP, Drupal & Symfony consulting Web Radio Telecommunications © 2012 Agavee GmbH Saturday, June 16, 12
  • 3. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 What’s Symfony2 A reusable set of standalone, decoupled, and cohesive PHP 5.3 components A full-stack web framework A Request/Response framework built around the HTTP specification A promoter of best practices, standardization and interoperability An awesome community! © 2012 Agavee GmbH Saturday, June 16, 12
  • 4. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Leave The STUPID Alone As time went by, habits and practices that once seemed acceptable have proven that they were making our code harder to understand and maintain. In other words, STUPID. But what makes code such a thing? • Singleton • Tight coupling • Untestability • Premature optimization • Indescriptive naming • Duplication © 2012 Agavee GmbH Saturday, June 16, 12
  • 5. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Singleton It’s a design pattern that restricts the creation of an object to one instance(think of a DB connection). It does introduce undesirable limitations(what if we’ll need TWO DB connections?), global state and hardcoded dependencies which are all making code more difficult to test and more coupled. © 2012 Agavee GmbH Saturday, June 16, 12
  • 6. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Singleton class DB {     private static $instance;     private function __construct()     { // ... code goes here ...     }     public static function getInstance()     {         if (empty(self::$instance)) {             self::$instance = new self;         }         return self::$instance;     } // ... more code goes here ... } © 2012 Agavee GmbH Saturday, June 16, 12
  • 7. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Tight Coupling It happens when classes are put in relation by using type hints, static calls or direct instantiation. Introduces hardcoded dependencies between classes, which complicates: • code reuse • unit testing • integration • modifications © 2012 Agavee GmbH Saturday, June 16, 12
  • 8. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Tight Coupling // An example of tight coupling class House {     public function __construct() {         $this->door = new Door();         $this->window = new Window();     } } // And a possible solution class House { // Door and Window are interfaces     public function __construct(Door $door, Window $window) {         $this->door = $door;         $this->window = $window;     } } © 2012 Agavee GmbH Saturday, June 16, 12
  • 9. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Untestability If classes are complex, tightly coupled or trying to do too much, then there’s a good chance that it’s also quite hard if not impossible to test it in isolation. The lack of proper test coverage will make code harder to maintain and change, as it becomes very difficult to tell if any modification is actually breaking something. © 2012 Agavee GmbH Saturday, June 16, 12
  • 10. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Premature Optimization Most of the time major performance issues are caused by small portions of code(80/20 rule). It is easier to optimize correct code than to correct optimized code. Performance are not always a concern, therefore optimize when it’s a proved problem, you’ll save time and raise productivity. © 2012 Agavee GmbH Saturday, June 16, 12
  • 11. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Indescriptive Naming There are two hard things in computer science: cache invalidation, naming things and off-by-one errors. -- Phil Karlton, variated by the Interwebs Even if hard, naming is a fundamental part of the job and should be considered part of the documentation, therefore remember to: • communicate intents • favor clarity over brevity • think that code is read far more often than written, so it’s more convenient to ease “reads” over “writes” © 2012 Agavee GmbH Saturday, June 16, 12
  • 12. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Duplication How many times did they tell you to not repeat yourself? © 2012 Agavee GmbH Saturday, June 16, 12
  • 13. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 BE SOLID! What alternatives to write STUPID code do we have? Another acronym to the rescue: SOLID! It encloses five class design principles: • Single responsibility principle • Open/closed principle • Liskov substitution principle • Interface segregation principle • Dependency inversion principle © 2012 Agavee GmbH Saturday, June 16, 12
  • 14. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Single Responsibility There should never be more than one reason for a class to change. Every class should have a single responsibility and fully encapsulate it. If change becomes localized, complexity and cost of change are reduced, moreover there’s less risk of ripple effects. © 2012 Agavee GmbH Saturday, June 16, 12
  • 15. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Single Responsibility interface Modem {     function dial($phoneNumber);     function hangup();     function send($message);     function receive(); } The above interface shows two responsibilities: connection management and data communication, making them good candidates for two separate interfaces/implementations. © 2012 Agavee GmbH Saturday, June 16, 12
  • 16. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Open/Closed Software entities (classes, functions, etc) should be open for extension, but closed for modification. This principle states that the source code of software entities shouldn’t ever be changed: those entities must be derived in order to add the wanted behaviors. Abstract Client Server Client Server Server © 2012 Agavee GmbH Saturday, June 16, 12
  • 17. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Liskov Substitution Objects in a program should be replaceable with instances of their subtypes without altering any of the desirable properties of that program, such as correctness and performed task. It intends to guarantee semantic interoperability of object types in a hierarchy. © 2012 Agavee GmbH Saturday, June 16, 12
  • 18. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Liskov Substitution class Rectangle { protected $width; protected $height;   function setWidth($width) {...} function draw(Rectangle $r) {   function getWidth() {...} $r->setWidth(5);   function setHeight($height) {...} $r->setHeight(4);   function getHeight() {...} } // is it correct to assume that changing the width of a Rectangle class Square extends Rectangle { leaves is height unchanged?   function setWidth($width) { assertEquals( $this->width = $width; 20, $this->height = $width; $r->setWidth() * $r->setHeight() } );   function setHeight($height) { } $this->width= $height; $this->height = $height; } } © 2012 Agavee GmbH Saturday, June 16, 12
  • 19. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Liskov Substitution The flaw in the Rectangle-Square design shows that even if conceptually a square is a rectangle, a Square object is not a Rectangle object, since a Square does not behave as a Rectangle. As a result, the public behavior the clients expect for the base class must be preserved in order to conform to the LSP. © 2012 Agavee GmbH Saturday, June 16, 12
  • 20. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Interface Segregation Many client-specific interfaces are better than one big one. This principle helps decreasing the coupling between objects by minimizing the intersecting surface. interface Printer {     function print(...); } interface MultiFunctionPrinter { interface Scanner     function print(...); {     function scan(...);     function print(...);     function fax(...); } } interface Fax {     function print(...); } © 2012 Agavee GmbH Saturday, June 16, 12
  • 21. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Dependency Inversion • High-level entities should not depend on low-level entities and both should depend on abstractions. • Abstractions should not depend upon details: details should depend upon abstractions. Component A Component A Service Component A Package Component B Component B Package © 2012 Agavee GmbH Saturday, June 16, 12
  • 22. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Dependency Inversion class Vehicle {     protected $tyres;     public function __construct() {         $this->tyres = array_fill(0, 4, new Tyre(50));     } } class Tyre {     private $diameter;     public function __construct($diameter) {         $this->setDiameter($diameter);     }     public function setDiameter($diameter) {         $this->diameter = $diameter;     }     public function getDiameter() {         return $this->diameter;     } } © 2012 Agavee GmbH Saturday, June 16, 12
  • 23. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Dependency Inversion namespace Vehicle; namespace Vehicle; class Vehicle { abstract class AbstractTyre {     protected $tyres;     private $diameter;     function addTyre(AbstractTyre $tyre) {     function __construct($diameter) {...}         $this->tyres[] = $tyre;     }     function setDiameter($diameter) {...} }     function getDiameter() {...} } namespace Tyre; use VehicleAbstractTyre; class RaceTyre extends AbstractTyre {     private $compound;     function setCompound($compound) {...}     function getCompound() {...} } © 2012 Agavee GmbH Saturday, June 16, 12
  • 24. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 How About Symfony Now? Being aware of the principles of software development mentioned earlier allow us to better understand some of the choices that have been made for the framework as well as some of the tools that have been made available, such as: • Class Loader • Service Container • Event Dispatcher • HTTP Foundation • HTTP Kernel © 2012 Agavee GmbH Saturday, June 16, 12
  • 25. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Class Loader It loads your project’s classes automatically if they’re following a standard PHP convention aka PSR-0. • DoctrineCommonIsolatedClassLoader => /path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php • SymfonyCoreRequest => /path/to/project/lib/vendor/Symfony/Core/Request.php • Twig_Node_Expression_Array => /path/to/project/lib/vendor/Twig/Node/Expression/Array.php It’s a great way to get out of the require_once hell while gaining better interoperability and lazy loading at the same time. © 2012 Agavee GmbH Saturday, June 16, 12
  • 26. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Service Container aka Dependency Injection Container A Service is any PHP object that performs a “global” task: think of a Mailer class. A Service Container is a special object (think of it as an Array of Objects on Steroids) that centralizes and standardizes the way objects are constructed inside an application: instead of directly creating Services, the developer configures the Container to take care of the task. © 2012 Agavee GmbH Saturday, June 16, 12
  • 27. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Event Dispatcher A lightweight implementation of the Observer Pattern, it provides a powerful and easy way to extend objects. Observer Observable +update +attach +detach +notify ConcreteObserver1 ConcreteObserver2 ConcreteObservable +update +update +attach +detach +notify © 2012 Agavee GmbH Saturday, June 16, 12
  • 28. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Event Dispatcher use SymfonyComponentEventDispatcherEventDispatcher; $dispatcher = new EventDispatcher(); $callable = function (Event $event) use ($log) { $log->addWarning(‘th3 n1nj4 d1sp4tch3r 1s 4ft3r y0u’); } $dispatcher->addListener(‘foo.bar’, $callable); $dispatcher->dispatch(‘foo.bar’, new Event()); © 2012 Agavee GmbH Saturday, June 16, 12
  • 29. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 HTTP Foundation It replaces the PHP’s global variables and functions that represent either requests or responses with a full-featured object-oriented layer for the HTTP messages. use SymfonyComponentHttpFoundationRequest; // http://example.com/?foo=bar $request = Request::createFromGlobals(); $request->query->get(‘foo’); // returns bar // simulate a request $request = Request::create('/foo', 'GET', array('name' => 'Bar')); use SymfonyComponentHttpFoundationResponse; $response = new Response('Content', 200, array( 'content-type' => 'text/html' )); // check the response is HTTP compliant and send it $response->prepare($request); $response->send(); © 2012 Agavee GmbH Saturday, June 16, 12
  • 30. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 HTTP Kernel The Kernel is the core of Symfony2: it is built on top of the HttpFoundation and its main goal is to “convert” a Request object into a Response object using a Controller, which in turn can be any kind of PHP callable. interface HttpKernelInterface {     const MASTER_REQUEST = 1;     const SUB_REQUEST = 2;     /** * ... * @return Response A Response instance * ... * @api */     function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true); } © 2012 Agavee GmbH Saturday, June 16, 12
  • 31. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 HTTP Kernel Workflow exception Sub- “sub-response” content Request exception resolve resolve call Request request controller controller response Response controller arguments view terminate © 2012 Agavee GmbH Saturday, June 16, 12
  • 32. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Symfony is not enough Let’s take a look at some of the most important third-party libraries © 2012 Agavee GmbH Saturday, June 16, 12
  • 33. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Doctrine2 The Doctrine Project is made of a selected set of PHP libraries primarily focused on providing persistence services and related functionality: • Common • Database Abstraction Layer • Object Relational Mapper • MongoDB Object Document Mapper • CouchDB Object Document Mapper • PHPCR Object Document Mapper • Migrations © 2012 Agavee GmbH Saturday, June 16, 12
  • 34. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Doctrine2 namespace DrupalBundleNodeBundleDocument; use DoctrineODMMongoDBMappingAnnotations as MongoDB; use DoctrineCommonPersistencePersistentObject; /** * @MongoDBDocument(collection="node") */ class Node extends PersistentObject {   /** * @MongoDBId */   protected $id;   /** * @MongoDBString */   protected $title; // accessor and mutators } © 2012 Agavee GmbH Saturday, June 16, 12
  • 35. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Twig A flexible, fast and secure template engine for PHP. It offers a great set of features, a concise syntax and very good performances (it compiles to PHP and has an optional C extension); moreover it’s super easy to extend and it’s thoughtfully documented. It gives the presentation layer a big boost in terms of expressiveness, making it more powerful and easier to use: prepare yourself for sweet hugs by front-end developers :) © 2012 Agavee GmbH Saturday, June 16, 12
  • 36. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Twig {# Node list page #} {% extends ‘layout.html.twig’ %} {% macro node_render(node) %} <div id=”node-{{node.id}}”> <h2>{{ node.title|title }}</h2> <div>{{ node.creationDate|date(‘d/m/Y’) }}</div> <div>{{ node.body }}</div> <div>{{ node.tags|join(‘, ‘) }}</div> </div> {% endmacro %} {% block body %} {% for node in nodes %} node_render(node); {% else %} {{ ‘We did not find any node.’|trans }} {% endfor %} {% endblock body %} © 2012 Agavee GmbH Saturday, June 16, 12
  • 37. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 © 2012 Agavee GmbH Saturday, June 16, 12
  • 38. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Assetic An advanced asset management framework for PHP. $css = new AssetCollection(array( new FileAsset('/path/to/src/styles.less', array(new LessFilter())), new GlobAsset('/path/to/css/*'), ), array( new YuiCssCompressorFilter('/path/to/yuicompressor.jar'), )); // this will echo CSS compiled by LESS and compressed by YUI echo $css->dump(); It ships with a strong set of filters for handling css, js, less, sass, compression, minifying and much more. Moreover, it’s nicely integrated with Twig. © 2012 Agavee GmbH Saturday, June 16, 12
  • 39. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Giving The Devil His Due Some resources I used to make these slides: • http://nikic.github.com/ • http://fabien.potencier.org/ • http://symfony.com/ • http://www.slideshare.net/jwage/symfony2-from-the-trenches • http://www.slideshare.net/weaverryan/handson-with-the-symfony2-framework • http://www.slideshare.net/weaverryan/symony2-a-next-generation-php-framework • http://martinfowler.com/articles/injection.html • http://www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod © 2012 Agavee GmbH Saturday, June 16, 12
  • 40. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 And Many Moar! Find many more Symfony2 Bundles and PHP Libraries at knpbundles.com and packagist.org! (and while you’re at it, take a look at Composer! ;) © 2012 Agavee GmbH Saturday, June 16, 12
  • 41. Drupal Developer Days 2012 Barcelona - Introducing Symfony2 Thank You! Claudio Beatrice @omissis © 2012 Agavee GmbH Saturday, June 16, 12