PHP 5.3 in practice

Fabien Potencier
Fabien PotencierCEO at Sensio
PHP 5.3 in practice

Fabien Potencier



   PHP 5.3 in practice – Fabien Potencier
Fabien Potencier
•  Serial entrepreneur and developer by passion
•  Founder of Sensio (in 1998)
   –  A services and consulting company
      specialized in Web technologies
      and Internet marketing (France and USA)
   –  70 people
   –  Open-Source specialists
   –  Big corporate customers
   –  Consulting, training, development, web design, … and more
   –  Sponsor of a lot of Open-Source projects
      like symfony and Doctrine
                               PHP 5.3 in practice – Fabien Potencier
Fabien Potencier
•  Creator and lead developer of symfony…
•  and creator and lead developer of some more OSS:
   –  Symfony components
   –  Swift Mailer : Powerful component based mailing library for PHP
   –  Twig : Fexible, fast, and secure template language for PHP
   –  Pirum : Simple PEAR Channel Server Manager
   –  Sismo : PHP continuous integration server
   –  Lime : Easy to use unit testing library for PHP
   –  Twitto : A web framework in a tweet
   –  Twittee : A Dependency Injection injector in a tweet
   –  Pimple : A small PHP 5.3 dependency injection injector

                                 PHP 5.3 in practice – Fabien Potencier
Fabien Potencier

•  Read my technical blog: http://fabien.potencier.org/

•  Follow me on Twitter: @fabpot

•  Fork my code on Github: http://github.com/fabpot/




                          PHP 5.3 in practice – Fabien Potencier
Migrating to PHP 5.3
… for technical reasons




  PHP 5.3 in practice – Fabien Potencier
Migrating to PHP 5.3?
•  Why?
  – Much faster
  – Less memory


•  When?
  – PHP 5.3.1 is available
  – PHP 5.3.2 is about to be released and stable
  – Migration is simple enough
                             PHP 5.3 in practice – Fabien Potencier
Migrating to PHP 5.3
… for speed




  PHP 5.3 in practice – Fabien Potencier
Dmitry Stogov did some benchmarks
                        for popular PHP applications

                            Drupal 20% faster
                             Typo3 30% faster
                          Wordpress 15% faster
                             Xoops 10% faster
http://news.php.net/php.internals/36484


                                PHP 5.3 in practice – Fabien Potencier
Doctrine 1.X and 2.0
Faster with PHP 5.3 and less memory consumption


         30% less memory

               20% faster


                PHP 5.3 in practice – Fabien Potencier
symfony 1




                                                                                                   -47%


symfony project running on PHP 5.2 vs PHP 5.3 profiled with XHPROF (run 4aeeb7d54b732 is PHP 5.3)



                                                    PHP 5.3 in practice – Fabien Potencier
Migrating to PHP 5.3
… for the ecosystem




  PHP 5.3 in practice – Fabien Potencier
Second generation of PHP frameworks
•  The next major versions of the most popular frameworks and libraries
   will use PHP 5.3
   –  Symfony 2.0
   –  Doctrine 2.0
                                       Late 2010
   –  Zend Framework 2.0


•  Better interoperability between these libraries, thanks to namespaces



                              PHP 5.3 in practice – Fabien Potencier
Namespaces and Symfony 2


SymfonyComponents
SymfonyFoundation
SymfonyFramework

SymfonyComponentsEventDispatcherEvent
SymfonyFoundationUniversalClassLoader


               PHP 5.3 in practice – Fabien Potencier
SymfonyComponentsEventDispatcherEvent


                              vs


                 sfEvent

                                                         Class names are
                                                           NOT shorter

                PHP 5.3 in practice – Fabien Potencier
Namespaces and Symfony 2

require __DIR__.'/lib/Symfony/Core/ClassLoader.php';

use SymfonyFoundationClassLoader;
use SymfonyComponentsEventDispatcherEvent;

$loader = new ClassLoader('Symfony', __DIR__.'/lib');
$loader->register();

$event = new Event();

                        PHP 5.3 in practice – Fabien Potencier
Namespaces and Symfony 2


require __DIR__.'/lib/Symfony/Core/ClassLoader.php';
use SymfonyFoundationClassLoader;
use SymfonyComponentsEventDispatcherEvent;

$loader = new ClassLoader('Symfony', __DIR__.'/lib');
$loader->register();

$event = new Event();


                        PHP 5.3 in practice – Fabien Potencier
PHP 5.3 technical interoperability standards

           « … describes the mandatory requirements
                     that must be adhered to
                for autoloader interoperability »


http://groups.google.com/group/php-standards/web/psr-0-final-proposal




                           PHP 5.3 in practice – Fabien Potencier
Why?
•  Libraries following the specification are interoperable

•  For instance, if you use Symfony 2.0, Doctrine 2.0, and Zend Framework
   2.0 in the same project
   –  They can all share the same autoloader
   –  Symfony 2.0 provides an enhanced autoloader (with PEAR support)
   –  A native C extension has been created




                                PHP 5.3 in practice – Fabien Potencier
Let’s dive into PHP 5.3




  PHP 5.3 in practice – Fabien Potencier
PHP 5.3
•  A lot of changes

   –  Convenient changes: __DIR__, ?:, NOWDOC, …

   –  New features: i18n, SPL, Date management, mysqlnd, …

   –  Language enhancements: namespaces, anonymous functions, closures, late
      static binding, phar, Windows support, …




                               PHP 5.3 in practice – Fabien Potencier
PHP 5.3

How does it change the implementation
of some well-known Design Pattern?


   PHP 5.3 in practice – Fabien Potencier
PHP 5.3
… and the Singleton




  PHP 5.3 in practice – Fabien Potencier
The Singleton may cause
     serious damage
       to your code
         PHP 5.3 in practice – Fabien Potencier
History of the Singleton




  PHP 5.3 in practice – Fabien Potencier
The Singleton in PHP 4
class Singleton
{
  function &getInstance()
  {
    static $instance;

        if (!$instance)
        {
          $instance = new Singleton();
        }


    }
        return $instance;                                                        You can still
}                                                                           ins tantiate the class
$obj =& Singleton::getInstance();
                                                                                    directly
                                   PHP 5.3 in practice – Fabien Potencier
The Singleton in PHP 5.0/5.1/5.2
class Singleton
{
  static private $instance;

    private function __construct() {}

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

        return self::$instance;

                                                                                  do not forget to
    }


}
    final private function __clone() {}
                                                                                 ove rride __clone()
$obj = Singleton::getInstance();
                                        PHP 5.3 in practice – Fabien Potencier
The Singleton in PHP 5.3
abstract class Singleton
{
  private static $instances = array();

    final private function __construct()
    {
      if (isset(self::$instances[get_called_class()]))
      {
        throw new Exception("An instance of ".get_called_class()." already exists.");
      }
      static::initialize();
    }

    protected function initialize() {}

    final public static function getInstance()
    {
      $class = get_called_class();
      if (!isset(self::$instances[$class]))
      {
        self::$instances[$class] = new static();
      }
      return self::$instances[$class];
    }

    final private function __clone() {}
}

                                                    PHP 5.3 in practice – Fabien Potencier
The Singleton in PHP 5.3

class Foo extends Singleton {}
class Bar extends Singleton {}

$a = Foo::getInstance();
$b = Bar::getInstance();




                      PHP 5.3 in practice – Fabien Potencier
PHP 5.3
…Late Static Binding

The ORM problem



   PHP 5.3 in practice – Fabien Potencier
class Model
{
  static public function getMe()
  {
    return __CLASS__;
  }
}

class Article extends Model {}

echo Article::getMe();

                   PHP 5.3 in practice – Fabien Potencier
<?php

class Model
{
  static public function getMe()
  {
    return get_called_class(); as of PHP 5.3
  }
}

class Article extends Model {}

echo Article::getMe();
                     PHP 5.3 in practice – Fabien Potencier
class Model
{
  static public function findByPk($id)
  {
    $table = strtolower(get_called_class());

        return $db->get(
         sprintf('SELECT * FROM %s WHERE id = %d', $table, $id)
        );
    }
}

class Article extends Model {}

$article = Article::findByPk(1);

                             PHP 5.3 in practice – Fabien Potencier
class Model
{
  static public function __callStatic($method, $arguments)
  {
    $table = strtolower(get_called_class());
    $column = strtolower(substr($method, 6));
    $value = $arguments[0];

    $sql = sprintf('SELECT * FROM %s WHERE %s = ?', $table,
$column);

        return $db->get($sql, $value);
    }
}

class Article extends Model {}

$article = Article::findByTitle('foo');
                               PHP 5.3 in practice – Fabien Potencier
PHP 5.3
…interlude

Anonymous functions
Lambdas


   PHP 5.3 in practice – Fabien Potencier
An anonymous function
                  is a function
           defined on the fly (no name)


function () { echo 'Hello world!'; };


                   PHP 5.3 in practice – Fabien Potencier
Can be stored in a variable

$hello = function () { echo 'Hello world!'; };




                     PHP 5.3 in practice – Fabien Potencier
… to be used later on


$hello();


call_user_func($hello);



                   PHP 5.3 in practice – Fabien Potencier
… or can be passed as a function argument

function foo(Closure $func)
{
  $func();
}

foo($hello);

                    PHP 5.3 in practice – Fabien Potencier
Fonctions anonymes
                    Can take arguments

$hello = function ($name) { echo 'Hello '.$name; };

$hello('Fabien');

call_user_func($hello, 'Fabien');




                            PHP 5.3 in practice – Fabien Potencier
Fonctions anonymes

function foo(Closure $func, $name)
{
  $func($name);
}

foo($hello, 'Fabien');




                         PHP 5.3 in practice – Fabien Potencier
When is it useful?




  PHP 5.3 in practice – Fabien Potencier
array_*
Greatly simplify usage of some array_* functions

  array_map()

  array_reduce()

  array_filter()




                              PHP 5.3 in practice – Fabien Potencier
class Article
{
  public function __construct($title)
  {
    $this->title = $title;
  }

    public function getTitle()
    {
      return $this->title;
    }
}
                     PHP 5.3 in practice – Fabien Potencier
How to get an array of all article titles?




$articles = array(
   new Article('PHP UK - part 1'),
   new Article('PHP UK - part 2'),
   new Article('See you next year!'),
);



                                 PHP 5.3 in practice – Fabien Potencier
$titles = array();
foreach ($articles as $article)
{
  $titles[] = $article->getTitle();
}



               PHP 5.3 in practice – Fabien Potencier
$titles = array_map(
   create_function('$article', 'return $article->getTitle();'),
   $articles
);




                          PHP 5.3 in practice – Fabien Potencier
$titles = array_map(
   function ($article) { return $article->getTitle(); },
   $articles
);




                       PHP 5.3 in practice – Fabien Potencier
$titles = array();
foreach ($articles as $article)
{
  $titles[] = $article->getTitle();
}

                                                                                100     100
$titles = array_map(create_function('$article', 'return $article->getTitle();'), $articles);

                                                                                300     1800
$titles = array_map(function ($article) { return $article->getTitle(); }, $articles);

                                                                                100     200
$mapper = function ($article) { return $article->getTitle(); };
$titles = array_map($mapper, $articles);

                                                                                100     180

      memory            speed

                                       PHP 5.3 in practice – Fabien Potencier
$mapper = function ($article) {
   return $article->getTitle();
};

$titles = array_map($mapper, $articles);

$mapper = function ($article) {
   return $article->getAuthor();
};

$authors = array_map($mapper, $articles);
                    PHP 5.3 in practice – Fabien Potencier
A closure is a lambda
that remembers the context
      of its creation…

        PHP 5.3 in practice – Fabien Potencier
$mapper = function ($method)
{
   return function ($article) use($method)
   {
      return $article->$method();
   };
};



                    PHP 5.3 in practice – Fabien Potencier
$method = 'getTitle';

$mapper = function ($article) use($method)
{
   return $article->$method();
};

$method = 'getAuthor';

$titles = array_map($mapper, $articles);

                   PHP 5.3 in practice – Fabien Potencier
$titleMapper = $mapper('getTitle');
$titles = array_map($titleMapper, $articles);


$authorMapper = $mapper('getAuthor');
$authors = array_map($authorMapper, $articles);



                   PHP 5.3 in practice – Fabien Potencier
$titles = array_map($mapper('getTitle'), $articles);


$authors = array_map($mapper('getAuthor'), $articles);




                      PHP 5.3 in practice – Fabien Potencier
Dependency Injector




  PHP 5.3 in practice – Fabien Potencier
« Dependency Injection is where components
 are given their dependencies through their
constructors, methods, or directly into fields. »

http://www.picoinjector.org/injection.html



                                             PHP 5.3 in practice – Fabien Potencier
Dependency Injection

A real world « web » example



   PHP 5.3 in practice – Fabien Potencier
In most web applications, you need to manage the user preferences

   –  The user language
   –  Whether the user is authenticated or not
   –  The user credentials
   –  …




                                 PHP 5.3 in practice – Fabien Potencier
This can be done with a User object

   –  setLanguage(), getLanguage()
   –  setAuthenticated(), isAuthenticated()
   –  addCredential(), hasCredential()
   –  ...




                              PHP 5.3 in practice – Fabien Potencier
The User information
         need to be persisted
        between HTTP requests

We use the PHP session for the Storage


             PHP 5.3 in practice – Fabien Potencier
class SessionStorage
{
  function __construct($cookieName = 'PHP_SESS_ID')
  {
    session_name($cookieName);
    session_start();
  }

    function set($key, $value)
    {
      $_SESSION[$key] = $value;
    }

    // ...
}

                            PHP 5.3 in practice – Fabien Potencier
class User
{
  protected $storage;

    function __construct()                                           Very hard to
    {                                                                 customize
      $this->storage = new SessionStorage();
    }

    function setLanguage($language)
    {
      $this->storage->set('language', $language);
    }

    // ...
}                         Very easy
                            to use
$user = new User();         PHP 5.3 in practice – Fabien Potencier
class User
{
  protected $storage;                                    Very easy to
                                                          customize
    function __construct($storage)
    {
      $this->storage = $storage;
    }
}

$storage = new SessionStorage();
$user = new User($storage);
                                                  Slightly more
                                                  difficult to use
                            PHP 5.3 in practice – Fabien Potencier
That’s Dependency Injection

      Nothing more


         PHP 5.3 in practice – Fabien Potencier
Instead of harcoding
    the Storage dependency
inside the User class constructor

Inject the Storage dependency
       in the User object

           PHP 5.3 in practice – Fabien Potencier
A Dependency Injector
      Describes objects
   and their dependencies

  Instantiates and configures
      objects on-demand
         PHP 5.3 in practice – Fabien Potencier
An injector
SHOULD be able to manage
  ANY PHP object (POPO)


The objects MUST not know
  that they are managed
      by the injector

      PHP 5.3 in practice – Fabien Potencier
•  Parameters
   –  The SessionStorage implementation we want to use (the class name)
   –  The session name
•  Objects
   –  SessionStorage
   –  User
•  Dependencies
   –  User depends on a SessionStorage implementation


                                PHP 5.3 in practice – Fabien Potencier
Let’s build a simple injector
with PHP 5.3




  PHP 5.3 in practice – Fabien Potencier
Dependency Injector

Managing parameters



   PHP 5.3 in practice – Fabien Potencier
class Injector
{
  protected $parameters = array();

    public function setParameter($key, $value)
    {
      $this->parameters[$key] = $value;
    }

    public function getParameter($key)
    {
      return $this->parameters[$key];
    }
}
                        PHP 5.3 in practice – Fabien Potencier
Decoupling


$injector = new Injector();                               Customization
$injector->setParameter('session_name', 'SESSION_ID');
$injector->setParameter('storage_class', 'SessionStorage');




$class = $injector->getParameter('storage_class');
$sessionStorage = new $class($injector->getParameter('session_name'));
$user = new User($sessionStorage);
                                                                      Objects creation

                             PHP 5.3 in practice – Fabien Potencier
class Injector                                                    Using PHP
{                                                                magic methods
  protected $parameters = array();

    public function __set($key, $value)
    {
      $this->parameters[$key] = $value;
    }

    public function __get($key)
    {
      return $this->parameters[$key];
    }
}
                        PHP 5.3 in practice – Fabien Potencier
Interface
                                                                       is cleaner


$injector = new Injector();
$injector->session_name = 'SESSION_ID';
$injector->storage_class = 'SessionStorage';

$sessionStorage = new $injector->storage_class($injector->session_name);
$user = new User($sessionStorage);




                              PHP 5.3 in practice – Fabien Potencier
Dependency Injector

Managing objects



   PHP 5.3 in practice – Fabien Potencier
We need a way to describe how to create objects,
    without actually instantiating anything!

      Anonymous functions to the rescue!

                  PHP 5.3 in practice – Fabien Potencier
class Injector
{
  protected $parameters = array();
  protected $objects = array();

    public function __set($key, $value)
    {
      $this->parameters[$key] = $value;
    }

    public function __get($key)                                                Store a lambda
    {
      return $this->parameters[$key];                                         able to create the
                                                                              object on-demand
    }

    public function setService($key, Closure $service)
    {
      $this->objects[$key] = $service;
    }

    public function getService($key)                              Ask the closure to create
    {
      return $this->objects[$key]($this);                          th e object and pass the
}
    }                                                                   current injector
                                     PHP 5.3 in practice – Fabien Potencier
$injector = new Injector();
$injector->session_name = 'SESSION_ID';                                         Description
$injector->storage_class = 'SessionStorage';
$injector->setService('user', function ($c)
{
  return new User($c->getService('storage'));
});
$injector->setService('storage', function ($c)
{
  return new $c->storage_class($c->session_name);
});


                                                                       Creating the User
                                                                   is now as easy as before
$user = $injector->getService('user');
                          PHP 5.3 in practice – Fabien Potencier
class Injector
{
  protected $values = array();                                            Simplify the code
    function __set($id, $value)
    {
      $this->values[$id] = $value;
    }

    function __get($id)
    {
      if (is_callable($this->values[$id]))
      {
        return $this->values[$id]($this);
      }
      else
      {
        return $this->values[$id];
      }
    }
}
                                 PHP 5.3 in practice – Fabien Potencier
$injector = new Injector();
                                            Unified interface
$injector->session_name = 'SESSION_ID';
$injector->storage_class = 'SessionStorage';
$injector->user = function ($c)
{
   return new User($c->storage);
};
$injector->storage = function ($c)
{
   return new $c->storage_class($c->session_name);
};




$user = $injector->user;
                           PHP 5.3 in practice – Fabien Potencier
Dependency Injector

Scope



   PHP 5.3 in practice – Fabien Potencier
For some objects, like the user,
    the injector must always
    return the same instance


          PHP 5.3 in practice – Fabien Potencier
spl_object_hash($injector->user)



            !==
spl_object_hash($injector->user)

            PHP 5.3 in practice – Fabien Potencier
$injector->user = function ($c)
{
  static $user;

  if (is_null($user))
  {
    $user = new User($c->storage);
  }

  return $user;
};
                   PHP 5.3 in practice – Fabien Potencier
spl_object_hash($injector->user)



            ===
spl_object_hash($injector->user)

            PHP 5.3 in practice – Fabien Potencier
$injector->user = $injector->asShared(function ($c)
{
  return new User($c->storage);
});




                      PHP 5.3 in practice – Fabien Potencier
function asShared(Closure $lambda)
{
  return function ($injector) use ($lambda)
  {
    static $object;

      if (is_null($object))
      {
        $object = $lambda($injector);
      }
      return $object;
    };
}
                     PHP 5.3 in practice – Fabien Potencier
class Injector
{
  protected $values = array();

    function __set($id, $value)
    {
      $this->values[$id] = $value;
    }

    function __get($id)
    {                                                                            Error management
      if (!isset($this->values[$id]))
      {
        throw new InvalidArgumentException(sprintf('Value "%s" is not defined.', $id));
      }

        if (is_callable($this->values[$id]))
        {
          return $this->values[$id]($this);
        }
        else
        {
          return $this->values[$id];
        }
    }
}                                       PHP 5.3 in practice – Fabien Potencier
class injector
{
  protected $values = array();

    function __set($id, $value)
    {
      $this->values[$id] = $value;
    }

    function __get($id)
    {
      if (!isset($this->values[$id]))
      {
        throw new InvalidArgumentException(sprintf('Value "%s" is not defined.', $id));
      }

        if (is_callable($this->values[$id]))
        {
          return $this->values[$id]($this);
        }
        else
        {
          return $this->values[$id];
        }
    }

    function asShared($callable)
    {


                                                                                                    40 LOC for a fully-
      return function ($c) use ($callable)
      {
        static $object;

          if (is_null($object))
          {
            $object = $callable($c);
                                                                                                     featured injector
          }
          return $object;
        };
    }
}                                                          PHP 5.3 in practice – Fabien Potencier
I’m NOT advocating
the usage of lambdas everywhere

  This presentation was about
    showing how they work
     on practical examples
            PHP 5.3 in practice – Fabien Potencier
Questions?




  PHP 5.3 in practice – Fabien Potencier
Sensio S.A.
    92-98, boulevard Victor Hugo
        92 115 Clichy Cedex
              FRANCE
       Tél. : +33 1 40 99 80 80

               Contact
           Fabien Potencier
    fabien.potencier at sensio.com




  http://www.sensiolabs.com/
http://www.symfony-project.org/
 http://fabien.potencier.org/


       PHP 5.3 in practice – Fabien Potencier
1 of 92

Recommended

Symfony Components 2.0 on PHP 5.3 by
Symfony Components 2.0 on PHP 5.3Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Fabien Potencier
18.6K views108 slides
Symfony Components by
Symfony ComponentsSymfony Components
Symfony Componentsguest0de7c2
1.9K views148 slides
New in php 7 by
New in php 7New in php 7
New in php 7Vic Metcalfe
1.1K views53 slides
Curso Symfony - Clase 4 by
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4Javier Eguiluz
2.1K views89 slides
Php mysql ppt by
Php mysql pptPhp mysql ppt
Php mysql pptKarmatechnologies Pvt. Ltd.
70.1K views39 slides
Short Intro to PHP and MySQL by
Short Intro to PHP and MySQLShort Intro to PHP and MySQL
Short Intro to PHP and MySQLJussi Pohjolainen
3.4K views48 slides

More Related Content

What's hot

Curso Symfony - Clase 2 by
Curso Symfony - Clase 2Curso Symfony - Clase 2
Curso Symfony - Clase 2Javier Eguiluz
1.8K views135 slides
Zephir - A Wind of Change for writing PHP extensions by
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsMark Baker
2.1K views53 slides
PHP Workshop Notes by
PHP Workshop NotesPHP Workshop Notes
PHP Workshop NotesPamela Fox
5.9K views29 slides
Intermediate PHP by
Intermediate PHPIntermediate PHP
Intermediate PHPBradley Holt
2.5K views78 slides
Design patterns in PHP by
Design patterns in PHPDesign patterns in PHP
Design patterns in PHPJason Straughan
4.5K views33 slides
Morpheus configuration engine (slides from Saint Perl-2 conference) by
Morpheus configuration engine (slides from Saint Perl-2 conference)Morpheus configuration engine (slides from Saint Perl-2 conference)
Morpheus configuration engine (slides from Saint Perl-2 conference)Vyacheslav Matyukhin
708 views43 slides

What's hot(18)

Zephir - A Wind of Change for writing PHP extensions by Mark Baker
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensions
Mark Baker2.1K views
PHP Workshop Notes by Pamela Fox
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox5.9K views
Morpheus configuration engine (slides from Saint Perl-2 conference) by Vyacheslav Matyukhin
Morpheus configuration engine (slides from Saint Perl-2 conference)Morpheus configuration engine (slides from Saint Perl-2 conference)
Morpheus configuration engine (slides from Saint Perl-2 conference)
Desenvolvendo em php cli by Thiago Paes
Desenvolvendo em php cliDesenvolvendo em php cli
Desenvolvendo em php cli
Thiago Paes12.8K views
PHP Powerpoint -- Teach PHP with this by Ian Macali
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Ian Macali54K views
Class 3 - PHP Functions by Ahmed Swilam
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
Ahmed Swilam2.4K views
TWIG: the flexible, fast and secure template language for PHP by Cesare D'Amico
TWIG: the flexible, fast and secure template language for PHPTWIG: the flexible, fast and secure template language for PHP
TWIG: the flexible, fast and secure template language for PHP
Cesare D'Amico4.6K views
07 Introduction to PHP #burningkeyboards by Denis Ristic
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
Denis Ristic342 views
Php Reusing Code And Writing Functions by mussawir20
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir204.5K views
PHP7. Game Changer. by Haim Michael
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
Haim Michael312 views
Class 2 - Introduction to PHP by Ahmed Swilam
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
Ahmed Swilam811 views

Viewers also liked

Look beyond PHP by
Look beyond PHPLook beyond PHP
Look beyond PHPFabien Potencier
9.5K views52 slides
Dependency injection-zendcon-2010 by
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
9.3K views103 slides
Design patterns revisited with PHP 5.3 by
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Fabien Potencier
67.1K views105 slides
Varnish by
VarnishVarnish
VarnishFabien Potencier
9K views107 slides
Dependency injection in PHP 5.3/5.4 by
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Fabien Potencier
37.4K views114 slides
symfony 1.1 goodness (Dutch PHP Conference 2008) by
symfony 1.1 goodness (Dutch PHP Conference 2008)symfony 1.1 goodness (Dutch PHP Conference 2008)
symfony 1.1 goodness (Dutch PHP Conference 2008)Fabien Potencier
6.2K views64 slides

Viewers also liked(16)

Dependency injection-zendcon-2010 by Fabien Potencier
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
Fabien Potencier9.3K views
Design patterns revisited with PHP 5.3 by Fabien Potencier
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3
Fabien Potencier67.1K views
Dependency injection in PHP 5.3/5.4 by Fabien Potencier
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
Fabien Potencier37.4K views
symfony 1.1 goodness (Dutch PHP Conference 2008) by Fabien Potencier
symfony 1.1 goodness (Dutch PHP Conference 2008)symfony 1.1 goodness (Dutch PHP Conference 2008)
symfony 1.1 goodness (Dutch PHP Conference 2008)
Fabien Potencier6.2K views
Dependency Injection - ConFoo 2010 by Fabien Potencier
Dependency Injection - ConFoo 2010Dependency Injection - ConFoo 2010
Dependency Injection - ConFoo 2010
Fabien Potencier1.3K views
Caching on the Edge with Symfony2 by Fabien Potencier
Caching on the Edge with Symfony2Caching on the Edge with Symfony2
Caching on the Edge with Symfony2
Fabien Potencier9.2K views
Unit and Functional Testing with Symfony2 by Fabien Potencier
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
Fabien Potencier20.4K views

Similar to PHP 5.3 in practice

Symfony 2.0 on PHP 5.3 by
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Fabien Potencier
3.5K views118 slides
ZendCon 08 php 5.3 by
ZendCon 08 php 5.3ZendCon 08 php 5.3
ZendCon 08 php 5.3webhostingguy
1K views24 slides
Simplify your professional web development with symfony by
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfonyFrancois Zaninotto
2.7K views40 slides
Unit testing symfony plugins with php unit by
Unit testing symfony plugins with php unitUnit testing symfony plugins with php unit
Unit testing symfony plugins with php unitChristian Schaefer
4.2K views17 slides
Design attern in php by
Design attern in phpDesign attern in php
Design attern in phpFilippo De Santis
1.6K views55 slides
How Symfony changed my life (#SfPot, Paris, 19th November 2015) by
How Symfony changed my life (#SfPot, Paris, 19th November 2015)How Symfony changed my life (#SfPot, Paris, 19th November 2015)
How Symfony changed my life (#SfPot, Paris, 19th November 2015)Matthias Noback
2.2K views68 slides

Similar to PHP 5.3 in practice(20)

Simplify your professional web development with symfony by Francois Zaninotto
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
Francois Zaninotto2.7K views
Unit testing symfony plugins with php unit by Christian Schaefer
Unit testing symfony plugins with php unitUnit testing symfony plugins with php unit
Unit testing symfony plugins with php unit
Christian Schaefer4.2K views
How Symfony changed my life (#SfPot, Paris, 19th November 2015) by Matthias Noback
How Symfony changed my life (#SfPot, Paris, 19th November 2015)How Symfony changed my life (#SfPot, Paris, 19th November 2015)
How Symfony changed my life (#SfPot, Paris, 19th November 2015)
Matthias Noback2.2K views
Php 7 compliance workshop singapore by Damien Seguy
Php 7 compliance workshop singaporePhp 7 compliance workshop singapore
Php 7 compliance workshop singapore
Damien Seguy369 views
関西アンカンファレンス PHP ではじめるテストコード by Shinya Ohyanagi
関西アンカンファレンス PHP ではじめるテストコード関西アンカンファレンス PHP ではじめるテストコード
関西アンカンファレンス PHP ではじめるテストコード
Shinya Ohyanagi1.5K views
Hands-on with the Symfony2 Framework by Ryan Weaver
Hands-on with the Symfony2 FrameworkHands-on with the Symfony2 Framework
Hands-on with the Symfony2 Framework
Ryan Weaver9.3K views
Symfony Live 09 Symfony 2 by narkoza
Symfony Live 09 Symfony 2Symfony Live 09 Symfony 2
Symfony Live 09 Symfony 2
narkoza1.9K views
Preparing code for Php 7 workshop by Damien Seguy
Preparing code for Php 7 workshopPreparing code for Php 7 workshop
Preparing code for Php 7 workshop
Damien Seguy914 views
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016 by Codemotion
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
Codemotion445 views
PHP 7.x - past, present, future (WordPress Varna #4) by Boyan Yordanov
PHP 7.x - past, present, future (WordPress Varna #4)PHP 7.x - past, present, future (WordPress Varna #4)
PHP 7.x - past, present, future (WordPress Varna #4)
Boyan Yordanov1.4K views
The why and how of moving to php 5.4 by Wim Godden
The why and how of moving to php 5.4The why and how of moving to php 5.4
The why and how of moving to php 5.4
Wim Godden2.6K views
oop_in_php_tutorial_for_killerphp.com by tutorialsruby
oop_in_php_tutorial_for_killerphp.comoop_in_php_tutorial_for_killerphp.com
oop_in_php_tutorial_for_killerphp.com
tutorialsruby397 views
Oop in php_tutorial_for_killerphp.com by ayandoesnotemail
Oop in php_tutorial_for_killerphp.comOop in php_tutorial_for_killerphp.com
Oop in php_tutorial_for_killerphp.com
ayandoesnotemail549 views

More from Fabien Potencier

Caching on the Edge by
Caching on the EdgeCaching on the Edge
Caching on the EdgeFabien Potencier
12.4K views141 slides
The state of Symfony2 - SymfonyDay 2010 by
The state of Symfony2 - SymfonyDay 2010The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010Fabien Potencier
1.9K views112 slides
Dependency injection - phpday 2010 by
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010Fabien Potencier
4.3K views103 slides
Symfony2 - WebExpo 2010 by
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Fabien Potencier
1.9K views127 slides
Symfony2 - WebExpo 2010 by
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Fabien Potencier
2.1K views127 slides
Symfony2 - OSIDays 2010 by
Symfony2 - OSIDays 2010Symfony2 - OSIDays 2010
Symfony2 - OSIDays 2010Fabien Potencier
1.3K views126 slides

More from Fabien Potencier(17)

The state of Symfony2 - SymfonyDay 2010 by Fabien Potencier
The state of Symfony2 - SymfonyDay 2010The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010
Fabien Potencier1.9K views
Dependency injection - phpday 2010 by Fabien Potencier
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
Fabien Potencier4.3K views
Dependency Injection with PHP and PHP 5.3 by Fabien Potencier
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier15.4K views
Symfony2 San Francisco Meetup 2009 by Fabien Potencier
Symfony2 San Francisco Meetup 2009Symfony2 San Francisco Meetup 2009
Symfony2 San Francisco Meetup 2009
Fabien Potencier1.4K views
Symfony And Zend Framework Together 2009 by Fabien Potencier
Symfony And Zend Framework Together 2009Symfony And Zend Framework Together 2009
Symfony And Zend Framework Together 2009
Fabien Potencier13K views
Twig, the flexible, fast, and secure template language for PHP by Fabien Potencier
Twig, the flexible, fast, and secure template language for PHPTwig, the flexible, fast, and secure template language for PHP
Twig, the flexible, fast, and secure template language for PHP
Fabien Potencier22.7K views
symfony: Un Framework Open-Source pour les Entreprises (Solutions Linux 2008) by Fabien Potencier
symfony: Un Framework Open-Source pour les Entreprises (Solutions Linux 2008)symfony: Un Framework Open-Source pour les Entreprises (Solutions Linux 2008)
symfony: Un Framework Open-Source pour les Entreprises (Solutions Linux 2008)
Fabien Potencier2K views
The symfony platform: Create your very own framework (PHP Quebec 2008) by Fabien Potencier
The symfony platform: Create your very own framework (PHP Quebec 2008)The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)
Fabien Potencier4.3K views

Recently uploaded

Mini-Track: AI and ML in Network Operations Applications by
Mini-Track: AI and ML in Network Operations ApplicationsMini-Track: AI and ML in Network Operations Applications
Mini-Track: AI and ML in Network Operations ApplicationsNetwork Automation Forum
10 views24 slides
Future of Indian ConsumerTech by
Future of Indian ConsumerTechFuture of Indian ConsumerTech
Future of Indian ConsumerTechKapil Khandelwal (KK)
22 views68 slides
Ransomware is Knocking your Door_Final.pdf by
Ransomware is Knocking your Door_Final.pdfRansomware is Knocking your Door_Final.pdf
Ransomware is Knocking your Door_Final.pdfSecurity Bootcamp
59 views46 slides
The Research Portal of Catalonia: Growing more (information) & more (services) by
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)CSUC - Consorci de Serveis Universitaris de Catalunya
80 views25 slides
PRODUCT PRESENTATION.pptx by
PRODUCT PRESENTATION.pptxPRODUCT PRESENTATION.pptx
PRODUCT PRESENTATION.pptxangelicacueva6
15 views1 slide
6g - REPORT.pdf by
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdfLiveplex
10 views23 slides

Recently uploaded(20)

6g - REPORT.pdf by Liveplex
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdf
Liveplex10 views
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2218 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10300 views
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf by Dr. Jimmy Schwarzkopf
STKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdfSTKI Israeli Market Study 2023   corrected forecast 2023_24 v3.pdf
STKI Israeli Market Study 2023 corrected forecast 2023_24 v3.pdf
Case Study Copenhagen Energy and Business Central.pdf by Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 views
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... by James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson92 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb14 views
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma39 views
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec12 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi132 views

PHP 5.3 in practice

  • 1. PHP 5.3 in practice Fabien Potencier PHP 5.3 in practice – Fabien Potencier
  • 2. Fabien Potencier •  Serial entrepreneur and developer by passion •  Founder of Sensio (in 1998) –  A services and consulting company specialized in Web technologies and Internet marketing (France and USA) –  70 people –  Open-Source specialists –  Big corporate customers –  Consulting, training, development, web design, … and more –  Sponsor of a lot of Open-Source projects like symfony and Doctrine PHP 5.3 in practice – Fabien Potencier
  • 3. Fabien Potencier •  Creator and lead developer of symfony… •  and creator and lead developer of some more OSS: –  Symfony components –  Swift Mailer : Powerful component based mailing library for PHP –  Twig : Fexible, fast, and secure template language for PHP –  Pirum : Simple PEAR Channel Server Manager –  Sismo : PHP continuous integration server –  Lime : Easy to use unit testing library for PHP –  Twitto : A web framework in a tweet –  Twittee : A Dependency Injection injector in a tweet –  Pimple : A small PHP 5.3 dependency injection injector PHP 5.3 in practice – Fabien Potencier
  • 4. Fabien Potencier •  Read my technical blog: http://fabien.potencier.org/ •  Follow me on Twitter: @fabpot •  Fork my code on Github: http://github.com/fabpot/ PHP 5.3 in practice – Fabien Potencier
  • 5. Migrating to PHP 5.3 … for technical reasons PHP 5.3 in practice – Fabien Potencier
  • 6. Migrating to PHP 5.3? •  Why? – Much faster – Less memory •  When? – PHP 5.3.1 is available – PHP 5.3.2 is about to be released and stable – Migration is simple enough PHP 5.3 in practice – Fabien Potencier
  • 7. Migrating to PHP 5.3 … for speed PHP 5.3 in practice – Fabien Potencier
  • 8. Dmitry Stogov did some benchmarks for popular PHP applications Drupal 20% faster Typo3 30% faster Wordpress 15% faster Xoops 10% faster http://news.php.net/php.internals/36484 PHP 5.3 in practice – Fabien Potencier
  • 9. Doctrine 1.X and 2.0 Faster with PHP 5.3 and less memory consumption 30% less memory 20% faster PHP 5.3 in practice – Fabien Potencier
  • 10. symfony 1 -47% symfony project running on PHP 5.2 vs PHP 5.3 profiled with XHPROF (run 4aeeb7d54b732 is PHP 5.3) PHP 5.3 in practice – Fabien Potencier
  • 11. Migrating to PHP 5.3 … for the ecosystem PHP 5.3 in practice – Fabien Potencier
  • 12. Second generation of PHP frameworks •  The next major versions of the most popular frameworks and libraries will use PHP 5.3 –  Symfony 2.0 –  Doctrine 2.0 Late 2010 –  Zend Framework 2.0 •  Better interoperability between these libraries, thanks to namespaces PHP 5.3 in practice – Fabien Potencier
  • 13. Namespaces and Symfony 2 SymfonyComponents SymfonyFoundation SymfonyFramework SymfonyComponentsEventDispatcherEvent SymfonyFoundationUniversalClassLoader PHP 5.3 in practice – Fabien Potencier
  • 14. SymfonyComponentsEventDispatcherEvent vs sfEvent Class names are NOT shorter PHP 5.3 in practice – Fabien Potencier
  • 15. Namespaces and Symfony 2 require __DIR__.'/lib/Symfony/Core/ClassLoader.php'; use SymfonyFoundationClassLoader; use SymfonyComponentsEventDispatcherEvent; $loader = new ClassLoader('Symfony', __DIR__.'/lib'); $loader->register(); $event = new Event(); PHP 5.3 in practice – Fabien Potencier
  • 16. Namespaces and Symfony 2 require __DIR__.'/lib/Symfony/Core/ClassLoader.php'; use SymfonyFoundationClassLoader; use SymfonyComponentsEventDispatcherEvent; $loader = new ClassLoader('Symfony', __DIR__.'/lib'); $loader->register(); $event = new Event(); PHP 5.3 in practice – Fabien Potencier
  • 17. PHP 5.3 technical interoperability standards « … describes the mandatory requirements that must be adhered to for autoloader interoperability » http://groups.google.com/group/php-standards/web/psr-0-final-proposal PHP 5.3 in practice – Fabien Potencier
  • 18. Why? •  Libraries following the specification are interoperable •  For instance, if you use Symfony 2.0, Doctrine 2.0, and Zend Framework 2.0 in the same project –  They can all share the same autoloader –  Symfony 2.0 provides an enhanced autoloader (with PEAR support) –  A native C extension has been created PHP 5.3 in practice – Fabien Potencier
  • 19. Let’s dive into PHP 5.3 PHP 5.3 in practice – Fabien Potencier
  • 20. PHP 5.3 •  A lot of changes –  Convenient changes: __DIR__, ?:, NOWDOC, … –  New features: i18n, SPL, Date management, mysqlnd, … –  Language enhancements: namespaces, anonymous functions, closures, late static binding, phar, Windows support, … PHP 5.3 in practice – Fabien Potencier
  • 21. PHP 5.3 How does it change the implementation of some well-known Design Pattern? PHP 5.3 in practice – Fabien Potencier
  • 22. PHP 5.3 … and the Singleton PHP 5.3 in practice – Fabien Potencier
  • 23. The Singleton may cause serious damage to your code PHP 5.3 in practice – Fabien Potencier
  • 24. History of the Singleton PHP 5.3 in practice – Fabien Potencier
  • 25. The Singleton in PHP 4 class Singleton { function &getInstance() { static $instance; if (!$instance) { $instance = new Singleton(); } } return $instance; You can still } ins tantiate the class $obj =& Singleton::getInstance(); directly PHP 5.3 in practice – Fabien Potencier
  • 26. The Singleton in PHP 5.0/5.1/5.2 class Singleton { static private $instance; private function __construct() {} static public function getInstance() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; do not forget to } } final private function __clone() {} ove rride __clone() $obj = Singleton::getInstance(); PHP 5.3 in practice – Fabien Potencier
  • 27. The Singleton in PHP 5.3 abstract class Singleton { private static $instances = array(); final private function __construct() { if (isset(self::$instances[get_called_class()])) { throw new Exception("An instance of ".get_called_class()." already exists."); } static::initialize(); } protected function initialize() {} final public static function getInstance() { $class = get_called_class(); if (!isset(self::$instances[$class])) { self::$instances[$class] = new static(); } return self::$instances[$class]; } final private function __clone() {} } PHP 5.3 in practice – Fabien Potencier
  • 28. The Singleton in PHP 5.3 class Foo extends Singleton {} class Bar extends Singleton {} $a = Foo::getInstance(); $b = Bar::getInstance(); PHP 5.3 in practice – Fabien Potencier
  • 29. PHP 5.3 …Late Static Binding The ORM problem PHP 5.3 in practice – Fabien Potencier
  • 30. class Model { static public function getMe() { return __CLASS__; } } class Article extends Model {} echo Article::getMe(); PHP 5.3 in practice – Fabien Potencier
  • 31. <?php class Model { static public function getMe() { return get_called_class(); as of PHP 5.3 } } class Article extends Model {} echo Article::getMe(); PHP 5.3 in practice – Fabien Potencier
  • 32. class Model { static public function findByPk($id) { $table = strtolower(get_called_class()); return $db->get( sprintf('SELECT * FROM %s WHERE id = %d', $table, $id) ); } } class Article extends Model {} $article = Article::findByPk(1); PHP 5.3 in practice – Fabien Potencier
  • 33. class Model { static public function __callStatic($method, $arguments) { $table = strtolower(get_called_class()); $column = strtolower(substr($method, 6)); $value = $arguments[0]; $sql = sprintf('SELECT * FROM %s WHERE %s = ?', $table, $column); return $db->get($sql, $value); } } class Article extends Model {} $article = Article::findByTitle('foo'); PHP 5.3 in practice – Fabien Potencier
  • 34. PHP 5.3 …interlude Anonymous functions Lambdas PHP 5.3 in practice – Fabien Potencier
  • 35. An anonymous function is a function defined on the fly (no name) function () { echo 'Hello world!'; }; PHP 5.3 in practice – Fabien Potencier
  • 36. Can be stored in a variable $hello = function () { echo 'Hello world!'; }; PHP 5.3 in practice – Fabien Potencier
  • 37. … to be used later on $hello(); call_user_func($hello); PHP 5.3 in practice – Fabien Potencier
  • 38. … or can be passed as a function argument function foo(Closure $func) { $func(); } foo($hello); PHP 5.3 in practice – Fabien Potencier
  • 39. Fonctions anonymes Can take arguments $hello = function ($name) { echo 'Hello '.$name; }; $hello('Fabien'); call_user_func($hello, 'Fabien'); PHP 5.3 in practice – Fabien Potencier
  • 40. Fonctions anonymes function foo(Closure $func, $name) { $func($name); } foo($hello, 'Fabien'); PHP 5.3 in practice – Fabien Potencier
  • 41. When is it useful? PHP 5.3 in practice – Fabien Potencier
  • 42. array_* Greatly simplify usage of some array_* functions array_map() array_reduce() array_filter() PHP 5.3 in practice – Fabien Potencier
  • 43. class Article { public function __construct($title) { $this->title = $title; } public function getTitle() { return $this->title; } } PHP 5.3 in practice – Fabien Potencier
  • 44. How to get an array of all article titles? $articles = array( new Article('PHP UK - part 1'), new Article('PHP UK - part 2'), new Article('See you next year!'), ); PHP 5.3 in practice – Fabien Potencier
  • 45. $titles = array(); foreach ($articles as $article) { $titles[] = $article->getTitle(); } PHP 5.3 in practice – Fabien Potencier
  • 46. $titles = array_map( create_function('$article', 'return $article->getTitle();'), $articles ); PHP 5.3 in practice – Fabien Potencier
  • 47. $titles = array_map( function ($article) { return $article->getTitle(); }, $articles ); PHP 5.3 in practice – Fabien Potencier
  • 48. $titles = array(); foreach ($articles as $article) { $titles[] = $article->getTitle(); } 100 100 $titles = array_map(create_function('$article', 'return $article->getTitle();'), $articles); 300 1800 $titles = array_map(function ($article) { return $article->getTitle(); }, $articles); 100 200 $mapper = function ($article) { return $article->getTitle(); }; $titles = array_map($mapper, $articles); 100 180 memory speed PHP 5.3 in practice – Fabien Potencier
  • 49. $mapper = function ($article) { return $article->getTitle(); }; $titles = array_map($mapper, $articles); $mapper = function ($article) { return $article->getAuthor(); }; $authors = array_map($mapper, $articles); PHP 5.3 in practice – Fabien Potencier
  • 50. A closure is a lambda that remembers the context of its creation… PHP 5.3 in practice – Fabien Potencier
  • 51. $mapper = function ($method) { return function ($article) use($method) { return $article->$method(); }; }; PHP 5.3 in practice – Fabien Potencier
  • 52. $method = 'getTitle'; $mapper = function ($article) use($method) { return $article->$method(); }; $method = 'getAuthor'; $titles = array_map($mapper, $articles); PHP 5.3 in practice – Fabien Potencier
  • 53. $titleMapper = $mapper('getTitle'); $titles = array_map($titleMapper, $articles); $authorMapper = $mapper('getAuthor'); $authors = array_map($authorMapper, $articles); PHP 5.3 in practice – Fabien Potencier
  • 54. $titles = array_map($mapper('getTitle'), $articles); $authors = array_map($mapper('getAuthor'), $articles); PHP 5.3 in practice – Fabien Potencier
  • 55. Dependency Injector PHP 5.3 in practice – Fabien Potencier
  • 56. « Dependency Injection is where components are given their dependencies through their constructors, methods, or directly into fields. » http://www.picoinjector.org/injection.html PHP 5.3 in practice – Fabien Potencier
  • 57. Dependency Injection A real world « web » example PHP 5.3 in practice – Fabien Potencier
  • 58. In most web applications, you need to manage the user preferences –  The user language –  Whether the user is authenticated or not –  The user credentials –  … PHP 5.3 in practice – Fabien Potencier
  • 59. This can be done with a User object –  setLanguage(), getLanguage() –  setAuthenticated(), isAuthenticated() –  addCredential(), hasCredential() –  ... PHP 5.3 in practice – Fabien Potencier
  • 60. The User information need to be persisted between HTTP requests We use the PHP session for the Storage PHP 5.3 in practice – Fabien Potencier
  • 61. class SessionStorage { function __construct($cookieName = 'PHP_SESS_ID') { session_name($cookieName); session_start(); } function set($key, $value) { $_SESSION[$key] = $value; } // ... } PHP 5.3 in practice – Fabien Potencier
  • 62. class User { protected $storage; function __construct() Very hard to { customize $this->storage = new SessionStorage(); } function setLanguage($language) { $this->storage->set('language', $language); } // ... } Very easy to use $user = new User(); PHP 5.3 in practice – Fabien Potencier
  • 63. class User { protected $storage; Very easy to customize function __construct($storage) { $this->storage = $storage; } } $storage = new SessionStorage(); $user = new User($storage); Slightly more difficult to use PHP 5.3 in practice – Fabien Potencier
  • 64. That’s Dependency Injection Nothing more PHP 5.3 in practice – Fabien Potencier
  • 65. Instead of harcoding the Storage dependency inside the User class constructor Inject the Storage dependency in the User object PHP 5.3 in practice – Fabien Potencier
  • 66. A Dependency Injector Describes objects and their dependencies Instantiates and configures objects on-demand PHP 5.3 in practice – Fabien Potencier
  • 67. An injector SHOULD be able to manage ANY PHP object (POPO) The objects MUST not know that they are managed by the injector PHP 5.3 in practice – Fabien Potencier
  • 68. •  Parameters –  The SessionStorage implementation we want to use (the class name) –  The session name •  Objects –  SessionStorage –  User •  Dependencies –  User depends on a SessionStorage implementation PHP 5.3 in practice – Fabien Potencier
  • 69. Let’s build a simple injector with PHP 5.3 PHP 5.3 in practice – Fabien Potencier
  • 70. Dependency Injector Managing parameters PHP 5.3 in practice – Fabien Potencier
  • 71. class Injector { protected $parameters = array(); public function setParameter($key, $value) { $this->parameters[$key] = $value; } public function getParameter($key) { return $this->parameters[$key]; } } PHP 5.3 in practice – Fabien Potencier
  • 72. Decoupling $injector = new Injector(); Customization $injector->setParameter('session_name', 'SESSION_ID'); $injector->setParameter('storage_class', 'SessionStorage'); $class = $injector->getParameter('storage_class'); $sessionStorage = new $class($injector->getParameter('session_name')); $user = new User($sessionStorage); Objects creation PHP 5.3 in practice – Fabien Potencier
  • 73. class Injector Using PHP { magic methods protected $parameters = array(); public function __set($key, $value) { $this->parameters[$key] = $value; } public function __get($key) { return $this->parameters[$key]; } } PHP 5.3 in practice – Fabien Potencier
  • 74. Interface is cleaner $injector = new Injector(); $injector->session_name = 'SESSION_ID'; $injector->storage_class = 'SessionStorage'; $sessionStorage = new $injector->storage_class($injector->session_name); $user = new User($sessionStorage); PHP 5.3 in practice – Fabien Potencier
  • 75. Dependency Injector Managing objects PHP 5.3 in practice – Fabien Potencier
  • 76. We need a way to describe how to create objects, without actually instantiating anything! Anonymous functions to the rescue! PHP 5.3 in practice – Fabien Potencier
  • 77. class Injector { protected $parameters = array(); protected $objects = array(); public function __set($key, $value) { $this->parameters[$key] = $value; } public function __get($key) Store a lambda { return $this->parameters[$key]; able to create the object on-demand } public function setService($key, Closure $service) { $this->objects[$key] = $service; } public function getService($key) Ask the closure to create { return $this->objects[$key]($this); th e object and pass the } } current injector PHP 5.3 in practice – Fabien Potencier
  • 78. $injector = new Injector(); $injector->session_name = 'SESSION_ID'; Description $injector->storage_class = 'SessionStorage'; $injector->setService('user', function ($c) { return new User($c->getService('storage')); }); $injector->setService('storage', function ($c) { return new $c->storage_class($c->session_name); }); Creating the User is now as easy as before $user = $injector->getService('user'); PHP 5.3 in practice – Fabien Potencier
  • 79. class Injector { protected $values = array(); Simplify the code function __set($id, $value) { $this->values[$id] = $value; } function __get($id) { if (is_callable($this->values[$id])) { return $this->values[$id]($this); } else { return $this->values[$id]; } } } PHP 5.3 in practice – Fabien Potencier
  • 80. $injector = new Injector(); Unified interface $injector->session_name = 'SESSION_ID'; $injector->storage_class = 'SessionStorage'; $injector->user = function ($c) { return new User($c->storage); }; $injector->storage = function ($c) { return new $c->storage_class($c->session_name); }; $user = $injector->user; PHP 5.3 in practice – Fabien Potencier
  • 81. Dependency Injector Scope PHP 5.3 in practice – Fabien Potencier
  • 82. For some objects, like the user, the injector must always return the same instance PHP 5.3 in practice – Fabien Potencier
  • 83. spl_object_hash($injector->user) !== spl_object_hash($injector->user) PHP 5.3 in practice – Fabien Potencier
  • 84. $injector->user = function ($c) { static $user; if (is_null($user)) { $user = new User($c->storage); } return $user; }; PHP 5.3 in practice – Fabien Potencier
  • 85. spl_object_hash($injector->user) === spl_object_hash($injector->user) PHP 5.3 in practice – Fabien Potencier
  • 86. $injector->user = $injector->asShared(function ($c) { return new User($c->storage); }); PHP 5.3 in practice – Fabien Potencier
  • 87. function asShared(Closure $lambda) { return function ($injector) use ($lambda) { static $object; if (is_null($object)) { $object = $lambda($injector); } return $object; }; } PHP 5.3 in practice – Fabien Potencier
  • 88. class Injector { protected $values = array(); function __set($id, $value) { $this->values[$id] = $value; } function __get($id) { Error management if (!isset($this->values[$id])) { throw new InvalidArgumentException(sprintf('Value "%s" is not defined.', $id)); } if (is_callable($this->values[$id])) { return $this->values[$id]($this); } else { return $this->values[$id]; } } } PHP 5.3 in practice – Fabien Potencier
  • 89. class injector { protected $values = array(); function __set($id, $value) { $this->values[$id] = $value; } function __get($id) { if (!isset($this->values[$id])) { throw new InvalidArgumentException(sprintf('Value "%s" is not defined.', $id)); } if (is_callable($this->values[$id])) { return $this->values[$id]($this); } else { return $this->values[$id]; } } function asShared($callable) { 40 LOC for a fully- return function ($c) use ($callable) { static $object; if (is_null($object)) { $object = $callable($c); featured injector } return $object; }; } } PHP 5.3 in practice – Fabien Potencier
  • 90. I’m NOT advocating the usage of lambdas everywhere This presentation was about showing how they work on practical examples PHP 5.3 in practice – Fabien Potencier
  • 91. Questions? PHP 5.3 in practice – Fabien Potencier
  • 92. Sensio S.A. 92-98, boulevard Victor Hugo 92 115 Clichy Cedex FRANCE Tél. : +33 1 40 99 80 80 Contact Fabien Potencier fabien.potencier at sensio.com http://www.sensiolabs.com/ http://www.symfony-project.org/ http://fabien.potencier.org/ PHP 5.3 in practice – Fabien Potencier