SlideShare a Scribd company logo
Zend Framework 2
quick start
by Enrico Zimuel (enrico@zend.com)

Senior Software Engineer
Zend Framework Core Team
Zend Technologies Ltd




ZFConf – 21th April 2012 Moscow
                                     © All rights reserved. Zend Technologies, Inc.
About me

                     • Enrico Zimuel (@ezimuel)
                     • Software Engineer since 1996
                            – Assembly x86, C/C++, Java, Perl, PHP
                     • Enjoying PHP since 1999
                     • PHP Engineer at Zend since 2008
                     • Zend Framework Core Team from
                                  2011
                     • B.Sc. Computer Science and
                                  Economics from University of
                                  Pescara (Italy)




           © All rights reserved. Zend Technologies, Inc.
Summary

●   Overview of ZF2
●   The new autoloading system
●   Dependency Injection
●   Event manager
●   The new MVC
●   Quick start: ZendSkeletonApplication
●   Package system
●   From ZF1 to ZF2

                    © All rights reserved. Zend Technologies, Inc.
ZF2 key features

●   New architecture (MVC, Di, Events)
●   Requirement: PHP 5.3
●   No more CLA (Contributor License Agreement)
●   Git (GitHub) instead of SVN
●   Better performance
●   Module management
●   Packaging system



                    © All rights reserved. Zend Technologies, Inc.
A new core

●   The ZF1 way:
       ▶   Singleton, Registry, and
             Hard-Coded Dependencies
●   The ZF2 approach:
       ▶   Aspect Oriented Design
             and Dependency Injection




                     © All rights reserved. Zend Technologies, Inc.
New architectural approach

●   Methodologies used in the development
      – Decoupling (ZendDi)
      – Event driven (ZendEventManager)
      – Standard classes (ZendStdlib)
●   Take advantage of PHP 5.3
       ▶   Namespace
       ▶   Lambda Functions and Closures
       ▶   Better performance


                     © All rights reserved. Zend Technologies, Inc.
Autoloading




  © All rights reserved. Zend Technologies, Inc.
Autoloading

●   No more require_once calls!
●   Multiple approaches:
      – ZF1-style include_path autoloader
      – Per-namespace/prefix autoloading
      – Class-map autoloading




                   © All rights reserved. Zend Technologies, Inc.
Classmap generator

●   How to generate the .classmap.php?
     We provided a command line tool:
     bin/classmap_generator.php
●   Usage is trivial:

    $ cd your/library
    $ php /path/to/classmap_generator.php -w

●   Class-Map will be created in .classmap.php




                        © All rights reserved. Zend Technologies, Inc.
Performance improvement

●   Class-Maps show a 25% improvement on the
      ZF1 autoloader when no acceleration is
      present
       ▶   60-85% improvements when an opcode cache
           is in place!

●   Pairing namespaces/prefixes with specific
     paths shows >10% gains with no
     acceleration
       ▶   40% improvements when an opcode cache is in
           place!

Note: The new autoloading system of ZF2 has been ported to ZF 1.12


                        © All rights reserved. Zend Technologies, Inc.
Dependency
 Injection



  © All rights reserved. Zend Technologies, Inc.
Dependency injection

●   How to manage dependencies between
    objects?
●   Dependency injection (Di) is
    a design pattern whose
    purpose is to reduce the
    coupling between software
    components




                                                        It's time for your dependency injection!

                 © All rights reserved. Zend Technologies, Inc.
Di by construct

        Without Di                                                 With Di (construct)

class Foo {                                                    class Foo {
  protected $bar;                                                 protected $bar;
  …                                                               …
  public function __construct() {                                 public function
    $this->bar= new Bar();                                          __construct(Bar $bar) {
  }                                                                  $this->bar = $bar;
  …                                                               }
}                                                                 …
                                                               }


 Cons:                                                              Pros:
 Difficult to test                                                  Easy to test
 No isolation                                                       Decoupling
 Difficult to reuse code                                            Flexible architecture
                           © All rights reserved. Zend Technologies, Inc.
Di by setter


class Foo
{
   protected $bar;
   …
   public function setBar(Bar $bar)
   {
      $this->bar = $bar;
   }
   …
}




                 © All rights reserved. Zend Technologies, Inc.
ZendDi

 ●   Supports the 3 different injection patterns:
       – Constructor
       – Interface
       – Setter
 ●   Implements a Di Container:
       – Manage the dependencies using configuration
           and annotation
       – Provide a compiler to autodiscover classes in a
            path and create the class definitions, for
            dependencies


                       © All rights reserved. Zend Technologies, Inc.
Sample definition

 $definition = array(
     'Foo' => array(
         'setBar' => array(
             'bar' => array(
                 'type'      => 'Bar',
                 'required' => true,
             ),
         ),
     ),
 );




                     © All rights reserved. Zend Technologies, Inc.
Using the Di container

 use ZendDiDi,
     ZendDiConfiguration;

 $di     = new Di;
 $config = new Configuration(array(
     'definition' => array('class' => $definition)
 ));
 $config->configure($di);

 $foo = $di->get('Foo'); // contains Bar!




                    © All rights reserved. Zend Technologies, Inc.
Di by annotation

namespace Example {
   use ZendDiDefinitionAnnotation as Di;

    class Foo {
       public $bam;
       /**
         * @DiInject()
         */
       public function setBar(Bar $bar){
            $this->bar = $bar;
       }
    }

    class Bar {
    }
}


                     © All rights reserved. Zend Technologies, Inc.
Di by annotation (2)


$compiler = new ZendDiDefinitionCompilerDefinition();
$compiler->addDirectory('File path of Foo and Bar');
$compiler->compile();

$definitions = new ZendDiDefinitionList($compiler);
$di = new ZendDiDi($definitions);

$baz = $di->get('ExampleFoo'); // contains Bar!




More use cases of ZendDi:
https://github.com/ralphschindler/zf2-di-use-cases


                     © All rights reserved. Zend Technologies, Inc.
Event Manager




   © All rights reserved. Zend Technologies, Inc.
Event Manager

●   An Event Manager is an object that
    aggregates listeners for one or more
    named events, and which triggers events.
●   A Listener is a callback that can react to
    an event.
●   An Event is an action.




                    © All rights reserved. Zend Technologies, Inc.
Example

use ZendEventManagerEventManager;

$events = new EventManager();
$events->attach('do', function($e) {
    $event = $e->getName();
    $params = $e->getParams();
    printf(
        'Handled event “%s”, with parameters %s',
        $event,
        json_encode($params)
    );
});
$params = array('foo' => 'bar', 'baz' => 'bat');
$events->trigger('do', null, $params);




                     © All rights reserved. Zend Technologies, Inc.
MVC



© All rights reserved. Zend Technologies, Inc.
Event driven architecture


●   Flow: bootstrap, route, dispatch, response
●   Everything is an event in MVC of ZF2




                    © All rights reserved. Zend Technologies, Inc.
Modules

●   The basic unit in a ZF2 MVC application is a Module
●   A module is a collection of code and other files that
    solves a more specific atomic problem of the larger
    business problem
●   Modules are simply:
       ▶   A namespace
       ▶   Containing a single classfile, Module.php




                       © All rights reserved. Zend Technologies, Inc.
Quick start
ZendSkeletonApplication




       © All rights reserved. Zend Technologies, Inc.
ZendSkeletonApplication

●   A simple, skeleton application using the ZF2
    MVC layer and module systems
●   On GitHub:
     ▶   git clone --recursive
         git://github.com/zendframework/ZendSkeletonApplication.git
●   This project makes use of Git submodules
●   Works using ZF2.0.0beta3




                         © All rights reserved. Zend Technologies, Inc.
Folder tree
   config                           autoload
                          application.config.php
   data

   module                          Application
                                               config
   vendor
                                               src
   public                                                 Application

       css                                                       Controller
                                                                 IndexController.php
       images
                                               view
       js
                                   Module.php
   .htaccess                       autoload_classmap.php
   index.php                       autoload_function.php
                                   autoload_register.php

                © All rights reserved. Zend Technologies, Inc.
Output




         © All rights reserved. Zend Technologies, Inc.
index.php

chdir(dirname(__DIR__));
require_once (getenv('ZF2_PATH') ?:
'vendor/ZendFramework/library') .
'/Zend/Loader/AutoloaderFactory.php';
ZendLoaderAutoloaderFactory::factory();

$appConfig = include 'config/application.config.php';

$listenerOptions = new ZendModuleListenerListenerOptions(
    $appConfig['module_listener_options']);
$defaultListeners = new
ZendModuleListenerDefaultListenerAggregate($listenerOptions);
$defaultListeners->getConfigListener()
                   ->addConfigGlobPath("config/autoload/{,*.}
{global,local}.config.php");
...




                      © All rights reserved. Zend Technologies, Inc.
index.php (2)

...
$moduleManager = new ZendModuleManager($appConfig['modules']);
$moduleManager->events()->attachAggregate($defaultListeners);
$moduleManager->loadModules();

// Create application, bootstrap, and run
$bootstrap   = new ZendMvcBootstrap(
   $defaultListeners->getConfigListener()->getMergedConfig());
$application = new ZendMvcApplication;
$bootstrap->bootstrap($application);
$application->run()->send();




                       © All rights reserved. Zend Technologies, Inc.
config/application.config.php

return array(
    'modules' => array(
        'Application'
    ),
    'module_listener_options' => array(
        'config_cache_enabled' => false,
        'cache_dir'            => 'data/cache',
        'module_paths' => array(
            './module',
            './vendor',
        ),
    ),
);




                    © All rights reserved. Zend Technologies, Inc.
config/autoload

●   global.config.php
●   local.config.php.dist (.gitignore)
●   By default, this application is configured to load all
    configs in:
     ./config/autoload/{,*.}{global,local}.config.php.
●   Doing this provides a location for a developer to drop in
    configuration override files provided by modules, as
    well as cleanly provide individual, application-wide
    config files for things like database connections, etc.




                        © All rights reserved. Zend Technologies, Inc.
Application/config/module.config.php


  return array(
      'di' => array(
          'instance' => array(
             …
          )
       )
  );

                 Here you configure the components
                 of your application (i.e. routing,
                 controller, view)




                 © All rights reserved. Zend Technologies, Inc.
IndexController.php


namespace ApplicationController;

use ZendMvcControllerActionController,
    ZendViewModelViewModel;

class IndexController extends ActionController
{
    public function indexAction()
    {
        return new ViewModel();
    }
}




                     © All rights reserved. Zend Technologies, Inc.
Modules are “plug and play”


●   Easy to reuse a module, only 3 steps:
1) Copy the module in module (or vendor) folder
2) Enable the module in your application.config.php
       ▶   Add the name of the module in “modules”
3) Copy the config file of the module in
  /config/autoload/module.<module's name>.config.php




                       © All rights reserved. Zend Technologies, Inc.
modules.zendframework.com




           © All rights reserved. Zend Technologies, Inc.
Package system




    © All rights reserved. Zend Technologies, Inc.
Package system
●   We use Pyrus, a tool to manage PEAR
    packages. Pyrus simplifies and improves the
    PEAR experience.
●   Source packages (download + github):
    ▶       http://packages.zendframework.com/
●   Install and configure pyrus:
    ▶       wget http://packages.zendframework.com/pyrus.phar
    ▶       pyrus.phar .
    ▶       pyrus.phar . channel-discover packages.zendframework.com

●   Install a Zend_<component>:
        ▶   pyrus.phar . install zf2/Zend_<component>




                             © All rights reserved. Zend Technologies, Inc.
From ZF1 to ZF2




     © All rights reserved. Zend Technologies, Inc.
Migrate to ZF2

●   Goal: migrate without rewriting much code!
●   Main steps
      – Namespace: Zend_Foo => ZendFoo
      – Exceptions: an Interface for each
          components, no more Zend_Exception
      – Autoloading: 3 possible options (one is
         ZF1)
       ▶   MVC: module, event based, dispatchable



                      © All rights reserved. Zend Technologies, Inc.
ZF1 migration prototype

●   Source code: http://bit.ly/pvc0X1
●   Creates a "Zf1Compat" version of the ZF1
    dispatcher as an event listener.
●   The bootstrap largely mimics how ZF1's
    Zend_Application bootstrap works.
●   The default route utilizes the new ZF2 MVC
    routing, but mimics what ZF1 provided.




                    © All rights reserved. Zend Technologies, Inc.
Helping out

●   http://framework.zend.com/zf2
●   http://github.com/zendframework
●   https://github.com/zendframework/ZendSkeletonApplication
●   Getting Started with Zend Framework 2 by Rob
    Allen, http://www.akrabat.com
●   Weekly IRC meetings (#zf2-meeting on Freenode)
●   #zftalk.2 on Freenode IRC




                       © All rights reserved. Zend Technologies, Inc.
Questions?




             © All rights reserved. Zend Technologies, Inc.
Thank you!

●   Comments and feedbacks:
     – Email: enrico@zend.com
     – Twitter: @ezimuel




                 © All rights reserved. Zend Technologies, Inc.

More Related Content

What's hot (20)

PDF
Zend Framework 2 Components
Shawn Stratton
 
PDF
Zend Framework 2 Patterns
Zend by Rogue Wave Software
 
PPTX
Get Started with Zend Framework 2
Mindfire Solutions
 
PDF
ZF2 Presentation @PHP Tour 2011 in Lille
Zend by Rogue Wave Software
 
PDF
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
Enrico Zimuel
 
PDF
Cryptography with Zend Framework
Enrico Zimuel
 
ODP
Introduction to Zend Framework
Michelangelo van Dam
 
PDF
Instant ACLs with Zend Framework 2
Stefano Valle
 
PPT
2007 Zend Con Mvc Edited Irmantas
Irmantas Šiupšinskas
 
KEY
Extending Zend_Tool
Ralph Schindler
 
PPTX
Zf2 phpquebec
mkherlakian
 
PDF
How to build customizable multitenant web applications - PHPBNL11
Stephan Hochdörfer
 
PPT
Using Zend_Tool to Establish Your Project's Skeleton
Jeremy Brown
 
PDF
Testing untestable code - phpday
Stephan Hochdörfer
 
PPT
A Zend Architecture presentation
techweb08
 
PDF
Apigility reloaded
Ralf Eggert
 
ODP
Java Code Generation for Productivity
David Noble
 
PPT
Symfony2 Service Container: Inject me, my friend
Kirill Chebunin
 
PDF
Symfony tips and tricks
Javier Eguiluz
 
PDF
Hierarchy Viewer Internals
Kyungmin Lee
 
Zend Framework 2 Components
Shawn Stratton
 
Zend Framework 2 Patterns
Zend by Rogue Wave Software
 
Get Started with Zend Framework 2
Mindfire Solutions
 
ZF2 Presentation @PHP Tour 2011 in Lille
Zend by Rogue Wave Software
 
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
Enrico Zimuel
 
Cryptography with Zend Framework
Enrico Zimuel
 
Introduction to Zend Framework
Michelangelo van Dam
 
Instant ACLs with Zend Framework 2
Stefano Valle
 
2007 Zend Con Mvc Edited Irmantas
Irmantas Šiupšinskas
 
Extending Zend_Tool
Ralph Schindler
 
Zf2 phpquebec
mkherlakian
 
How to build customizable multitenant web applications - PHPBNL11
Stephan Hochdörfer
 
Using Zend_Tool to Establish Your Project's Skeleton
Jeremy Brown
 
Testing untestable code - phpday
Stephan Hochdörfer
 
A Zend Architecture presentation
techweb08
 
Apigility reloaded
Ralf Eggert
 
Java Code Generation for Productivity
David Noble
 
Symfony2 Service Container: Inject me, my friend
Kirill Chebunin
 
Symfony tips and tricks
Javier Eguiluz
 
Hierarchy Viewer Internals
Kyungmin Lee
 

Similar to Zend Framework 2 quick start (20)

PDF
How to Manage Cloud Infrastructures using Zend Framework
Zend by Rogue Wave Software
 
PDF
Eclipse HandsOn Workshop
Bastian Feder
 
PPTX
Z ray plugins for dummies
Dmitry Zbarski
 
PDF
Getting Native with NDK
ナム-Nam Nguyễn
 
PDF
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
James Titcumb
 
PDF
Php Development With Eclipde PDT
Bastian Feder
 
PDF
Configuration Management and Transforming Legacy Applications in the Enterpri...
Docker, Inc.
 
PDF
Extension and Evolution
Eelco Visser
 
PDF
Bangpypers april-meetup-2012
Deepak Garg
 
PDF
Ростислав Михайлив "Zend Framework 3 - evolution or revolution"
Fwdays
 
PDF
Head First Zend Framework - Part 1 Project & Application
Jace Ju
 
PDF
Php7 extensions workshop
julien pauli
 
PDF
2010 07-28-testing-zf-apps
Venkata Ramana
 
PDF
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Bastian Feder
 
PDF
Eclipse Pdt2.0 26.05.2009
Bastian Feder
 
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
James Titcumb
 
PDF
Debugging PHP with xDebug inside of Eclipse PDT 2.1
Bastian Feder
 
PPTX
PHP Development Tools 2.0 - Success Story
Michael Spector
 
PPTX
drupal ci cd concept cornel univercity.pptx
rukuntravel
 
PDF
Foundations of Zend Framework
Adam Culp
 
How to Manage Cloud Infrastructures using Zend Framework
Zend by Rogue Wave Software
 
Eclipse HandsOn Workshop
Bastian Feder
 
Z ray plugins for dummies
Dmitry Zbarski
 
Getting Native with NDK
ナム-Nam Nguyễn
 
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
James Titcumb
 
Php Development With Eclipde PDT
Bastian Feder
 
Configuration Management and Transforming Legacy Applications in the Enterpri...
Docker, Inc.
 
Extension and Evolution
Eelco Visser
 
Bangpypers april-meetup-2012
Deepak Garg
 
Ростислав Михайлив "Zend Framework 3 - evolution or revolution"
Fwdays
 
Head First Zend Framework - Part 1 Project & Application
Jace Ju
 
Php7 extensions workshop
julien pauli
 
2010 07-28-testing-zf-apps
Venkata Ramana
 
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Bastian Feder
 
Eclipse Pdt2.0 26.05.2009
Bastian Feder
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
James Titcumb
 
Debugging PHP with xDebug inside of Eclipse PDT 2.1
Bastian Feder
 
PHP Development Tools 2.0 - Success Story
Michael Spector
 
drupal ci cd concept cornel univercity.pptx
rukuntravel
 
Foundations of Zend Framework
Adam Culp
 
Ad

More from Enrico Zimuel (20)

PDF
Password (in)security
Enrico Zimuel
 
PDF
Integrare Zend Framework in Wordpress
Enrico Zimuel
 
PDF
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
Enrico Zimuel
 
PDF
PHP goes mobile
Enrico Zimuel
 
PDF
Zend Framework 2
Enrico Zimuel
 
PDF
Cryptography in PHP: use cases
Enrico Zimuel
 
PDF
Framework software e Zend Framework
Enrico Zimuel
 
PDF
Strong cryptography in PHP
Enrico Zimuel
 
PDF
How to scale PHP applications
Enrico Zimuel
 
PDF
Velocizzare Joomla! con Zend Server Community Edition
Enrico Zimuel
 
PDF
Zend_Cache: how to improve the performance of PHP applications
Enrico Zimuel
 
PDF
XCheck a benchmark checker for XML query processors
Enrico Zimuel
 
PDF
Introduzione alle tabelle hash
Enrico Zimuel
 
PDF
Crittografia quantistica: fantascienza o realtà?
Enrico Zimuel
 
PDF
Introduzione alla crittografia
Enrico Zimuel
 
PDF
Crittografia è sinonimo di sicurezza?
Enrico Zimuel
 
PDF
Sviluppo di applicazioni sicure
Enrico Zimuel
 
PDF
Misure minime di sicurezza informatica
Enrico Zimuel
 
PDF
PHP e crittografia
Enrico Zimuel
 
PDF
La sicurezza delle applicazioni in PHP
Enrico Zimuel
 
Password (in)security
Enrico Zimuel
 
Integrare Zend Framework in Wordpress
Enrico Zimuel
 
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
Enrico Zimuel
 
PHP goes mobile
Enrico Zimuel
 
Zend Framework 2
Enrico Zimuel
 
Cryptography in PHP: use cases
Enrico Zimuel
 
Framework software e Zend Framework
Enrico Zimuel
 
Strong cryptography in PHP
Enrico Zimuel
 
How to scale PHP applications
Enrico Zimuel
 
Velocizzare Joomla! con Zend Server Community Edition
Enrico Zimuel
 
Zend_Cache: how to improve the performance of PHP applications
Enrico Zimuel
 
XCheck a benchmark checker for XML query processors
Enrico Zimuel
 
Introduzione alle tabelle hash
Enrico Zimuel
 
Crittografia quantistica: fantascienza o realtà?
Enrico Zimuel
 
Introduzione alla crittografia
Enrico Zimuel
 
Crittografia è sinonimo di sicurezza?
Enrico Zimuel
 
Sviluppo di applicazioni sicure
Enrico Zimuel
 
Misure minime di sicurezza informatica
Enrico Zimuel
 
PHP e crittografia
Enrico Zimuel
 
La sicurezza delle applicazioni in PHP
Enrico Zimuel
 
Ad

Recently uploaded (20)

PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 

Zend Framework 2 quick start

  • 1. Zend Framework 2 quick start by Enrico Zimuel ([email protected]) Senior Software Engineer Zend Framework Core Team Zend Technologies Ltd ZFConf – 21th April 2012 Moscow © All rights reserved. Zend Technologies, Inc.
  • 2. About me • Enrico Zimuel (@ezimuel) • Software Engineer since 1996 – Assembly x86, C/C++, Java, Perl, PHP • Enjoying PHP since 1999 • PHP Engineer at Zend since 2008 • Zend Framework Core Team from 2011 • B.Sc. Computer Science and Economics from University of Pescara (Italy) © All rights reserved. Zend Technologies, Inc.
  • 3. Summary ● Overview of ZF2 ● The new autoloading system ● Dependency Injection ● Event manager ● The new MVC ● Quick start: ZendSkeletonApplication ● Package system ● From ZF1 to ZF2 © All rights reserved. Zend Technologies, Inc.
  • 4. ZF2 key features ● New architecture (MVC, Di, Events) ● Requirement: PHP 5.3 ● No more CLA (Contributor License Agreement) ● Git (GitHub) instead of SVN ● Better performance ● Module management ● Packaging system © All rights reserved. Zend Technologies, Inc.
  • 5. A new core ● The ZF1 way: ▶ Singleton, Registry, and Hard-Coded Dependencies ● The ZF2 approach: ▶ Aspect Oriented Design and Dependency Injection © All rights reserved. Zend Technologies, Inc.
  • 6. New architectural approach ● Methodologies used in the development – Decoupling (ZendDi) – Event driven (ZendEventManager) – Standard classes (ZendStdlib) ● Take advantage of PHP 5.3 ▶ Namespace ▶ Lambda Functions and Closures ▶ Better performance © All rights reserved. Zend Technologies, Inc.
  • 7. Autoloading © All rights reserved. Zend Technologies, Inc.
  • 8. Autoloading ● No more require_once calls! ● Multiple approaches: – ZF1-style include_path autoloader – Per-namespace/prefix autoloading – Class-map autoloading © All rights reserved. Zend Technologies, Inc.
  • 9. Classmap generator ● How to generate the .classmap.php? We provided a command line tool: bin/classmap_generator.php ● Usage is trivial: $ cd your/library $ php /path/to/classmap_generator.php -w ● Class-Map will be created in .classmap.php © All rights reserved. Zend Technologies, Inc.
  • 10. Performance improvement ● Class-Maps show a 25% improvement on the ZF1 autoloader when no acceleration is present ▶ 60-85% improvements when an opcode cache is in place! ● Pairing namespaces/prefixes with specific paths shows >10% gains with no acceleration ▶ 40% improvements when an opcode cache is in place! Note: The new autoloading system of ZF2 has been ported to ZF 1.12 © All rights reserved. Zend Technologies, Inc.
  • 11. Dependency Injection © All rights reserved. Zend Technologies, Inc.
  • 12. Dependency injection ● How to manage dependencies between objects? ● Dependency injection (Di) is a design pattern whose purpose is to reduce the coupling between software components It's time for your dependency injection! © All rights reserved. Zend Technologies, Inc.
  • 13. Di by construct Without Di With Di (construct) class Foo { class Foo { protected $bar; protected $bar; … … public function __construct() { public function $this->bar= new Bar(); __construct(Bar $bar) { } $this->bar = $bar; … } } … } Cons: Pros: Difficult to test Easy to test No isolation Decoupling Difficult to reuse code Flexible architecture © All rights reserved. Zend Technologies, Inc.
  • 14. Di by setter class Foo { protected $bar; … public function setBar(Bar $bar) { $this->bar = $bar; } … } © All rights reserved. Zend Technologies, Inc.
  • 15. ZendDi ● Supports the 3 different injection patterns: – Constructor – Interface – Setter ● Implements a Di Container: – Manage the dependencies using configuration and annotation – Provide a compiler to autodiscover classes in a path and create the class definitions, for dependencies © All rights reserved. Zend Technologies, Inc.
  • 16. Sample definition $definition = array( 'Foo' => array( 'setBar' => array( 'bar' => array( 'type' => 'Bar', 'required' => true, ), ), ), ); © All rights reserved. Zend Technologies, Inc.
  • 17. Using the Di container use ZendDiDi, ZendDiConfiguration; $di = new Di; $config = new Configuration(array( 'definition' => array('class' => $definition) )); $config->configure($di); $foo = $di->get('Foo'); // contains Bar! © All rights reserved. Zend Technologies, Inc.
  • 18. Di by annotation namespace Example { use ZendDiDefinitionAnnotation as Di; class Foo { public $bam; /** * @DiInject() */ public function setBar(Bar $bar){ $this->bar = $bar; } } class Bar { } } © All rights reserved. Zend Technologies, Inc.
  • 19. Di by annotation (2) $compiler = new ZendDiDefinitionCompilerDefinition(); $compiler->addDirectory('File path of Foo and Bar'); $compiler->compile(); $definitions = new ZendDiDefinitionList($compiler); $di = new ZendDiDi($definitions); $baz = $di->get('ExampleFoo'); // contains Bar! More use cases of ZendDi: https://github.com/ralphschindler/zf2-di-use-cases © All rights reserved. Zend Technologies, Inc.
  • 20. Event Manager © All rights reserved. Zend Technologies, Inc.
  • 21. Event Manager ● An Event Manager is an object that aggregates listeners for one or more named events, and which triggers events. ● A Listener is a callback that can react to an event. ● An Event is an action. © All rights reserved. Zend Technologies, Inc.
  • 22. Example use ZendEventManagerEventManager; $events = new EventManager(); $events->attach('do', function($e) { $event = $e->getName(); $params = $e->getParams(); printf( 'Handled event “%s”, with parameters %s', $event, json_encode($params) ); }); $params = array('foo' => 'bar', 'baz' => 'bat'); $events->trigger('do', null, $params); © All rights reserved. Zend Technologies, Inc.
  • 23. MVC © All rights reserved. Zend Technologies, Inc.
  • 24. Event driven architecture ● Flow: bootstrap, route, dispatch, response ● Everything is an event in MVC of ZF2 © All rights reserved. Zend Technologies, Inc.
  • 25. Modules ● The basic unit in a ZF2 MVC application is a Module ● A module is a collection of code and other files that solves a more specific atomic problem of the larger business problem ● Modules are simply: ▶ A namespace ▶ Containing a single classfile, Module.php © All rights reserved. Zend Technologies, Inc.
  • 26. Quick start ZendSkeletonApplication © All rights reserved. Zend Technologies, Inc.
  • 27. ZendSkeletonApplication ● A simple, skeleton application using the ZF2 MVC layer and module systems ● On GitHub: ▶ git clone --recursive git://github.com/zendframework/ZendSkeletonApplication.git ● This project makes use of Git submodules ● Works using ZF2.0.0beta3 © All rights reserved. Zend Technologies, Inc.
  • 28. Folder tree config autoload application.config.php data module Application config vendor src public Application css Controller IndexController.php images view js Module.php .htaccess autoload_classmap.php index.php autoload_function.php autoload_register.php © All rights reserved. Zend Technologies, Inc.
  • 29. Output © All rights reserved. Zend Technologies, Inc.
  • 30. index.php chdir(dirname(__DIR__)); require_once (getenv('ZF2_PATH') ?: 'vendor/ZendFramework/library') . '/Zend/Loader/AutoloaderFactory.php'; ZendLoaderAutoloaderFactory::factory(); $appConfig = include 'config/application.config.php'; $listenerOptions = new ZendModuleListenerListenerOptions( $appConfig['module_listener_options']); $defaultListeners = new ZendModuleListenerDefaultListenerAggregate($listenerOptions); $defaultListeners->getConfigListener() ->addConfigGlobPath("config/autoload/{,*.} {global,local}.config.php"); ... © All rights reserved. Zend Technologies, Inc.
  • 31. index.php (2) ... $moduleManager = new ZendModuleManager($appConfig['modules']); $moduleManager->events()->attachAggregate($defaultListeners); $moduleManager->loadModules(); // Create application, bootstrap, and run $bootstrap = new ZendMvcBootstrap( $defaultListeners->getConfigListener()->getMergedConfig()); $application = new ZendMvcApplication; $bootstrap->bootstrap($application); $application->run()->send(); © All rights reserved. Zend Technologies, Inc.
  • 32. config/application.config.php return array( 'modules' => array( 'Application' ), 'module_listener_options' => array( 'config_cache_enabled' => false, 'cache_dir' => 'data/cache', 'module_paths' => array( './module', './vendor', ), ), ); © All rights reserved. Zend Technologies, Inc.
  • 33. config/autoload ● global.config.php ● local.config.php.dist (.gitignore) ● By default, this application is configured to load all configs in: ./config/autoload/{,*.}{global,local}.config.php. ● Doing this provides a location for a developer to drop in configuration override files provided by modules, as well as cleanly provide individual, application-wide config files for things like database connections, etc. © All rights reserved. Zend Technologies, Inc.
  • 34. Application/config/module.config.php return array( 'di' => array( 'instance' => array( … ) ) ); Here you configure the components of your application (i.e. routing, controller, view) © All rights reserved. Zend Technologies, Inc.
  • 35. IndexController.php namespace ApplicationController; use ZendMvcControllerActionController, ZendViewModelViewModel; class IndexController extends ActionController { public function indexAction() { return new ViewModel(); } } © All rights reserved. Zend Technologies, Inc.
  • 36. Modules are “plug and play” ● Easy to reuse a module, only 3 steps: 1) Copy the module in module (or vendor) folder 2) Enable the module in your application.config.php ▶ Add the name of the module in “modules” 3) Copy the config file of the module in /config/autoload/module.<module's name>.config.php © All rights reserved. Zend Technologies, Inc.
  • 37. modules.zendframework.com © All rights reserved. Zend Technologies, Inc.
  • 38. Package system © All rights reserved. Zend Technologies, Inc.
  • 39. Package system ● We use Pyrus, a tool to manage PEAR packages. Pyrus simplifies and improves the PEAR experience. ● Source packages (download + github): ▶ http://packages.zendframework.com/ ● Install and configure pyrus: ▶ wget http://packages.zendframework.com/pyrus.phar ▶ pyrus.phar . ▶ pyrus.phar . channel-discover packages.zendframework.com ● Install a Zend_<component>: ▶ pyrus.phar . install zf2/Zend_<component> © All rights reserved. Zend Technologies, Inc.
  • 40. From ZF1 to ZF2 © All rights reserved. Zend Technologies, Inc.
  • 41. Migrate to ZF2 ● Goal: migrate without rewriting much code! ● Main steps – Namespace: Zend_Foo => ZendFoo – Exceptions: an Interface for each components, no more Zend_Exception – Autoloading: 3 possible options (one is ZF1) ▶ MVC: module, event based, dispatchable © All rights reserved. Zend Technologies, Inc.
  • 42. ZF1 migration prototype ● Source code: http://bit.ly/pvc0X1 ● Creates a "Zf1Compat" version of the ZF1 dispatcher as an event listener. ● The bootstrap largely mimics how ZF1's Zend_Application bootstrap works. ● The default route utilizes the new ZF2 MVC routing, but mimics what ZF1 provided. © All rights reserved. Zend Technologies, Inc.
  • 43. Helping out ● http://framework.zend.com/zf2 ● http://github.com/zendframework ● https://github.com/zendframework/ZendSkeletonApplication ● Getting Started with Zend Framework 2 by Rob Allen, http://www.akrabat.com ● Weekly IRC meetings (#zf2-meeting on Freenode) ● #zftalk.2 on Freenode IRC © All rights reserved. Zend Technologies, Inc.
  • 44. Questions? © All rights reserved. Zend Technologies, Inc.
  • 45. Thank you! ● Comments and feedbacks: – Email: [email protected] – Twitter: @ezimuel © All rights reserved. Zend Technologies, Inc.