SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

How to build customizable multitenant web applications - PHPBNL11
How to build customizable multitenant web applications - PHPBNL11How to build customizable multitenant web applications - PHPBNL11
How to build customizable multitenant web applications - PHPBNL11
Stephan Hochdörfer
 
Testing untestable code - phpday
Testing untestable code - phpdayTesting untestable code - phpday
Testing untestable code - phpday
Stephan Hochdörfer
 
A Zend Architecture presentation
A Zend Architecture presentationA Zend Architecture presentation
A Zend Architecture presentation
techweb08
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friendSymfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friend
Kirill Chebunin
 

Was ist angesagt? (20)

Zend Framework 2 Components
Zend Framework 2 ComponentsZend Framework 2 Components
Zend Framework 2 Components
 
Zend Framework 2 Patterns
Zend Framework 2 PatternsZend Framework 2 Patterns
Zend Framework 2 Patterns
 
Get Started with Zend Framework 2
Get Started with Zend Framework 2Get Started with Zend Framework 2
Get Started with Zend Framework 2
 
ZF2 Presentation @PHP Tour 2011 in Lille
ZF2 Presentation @PHP Tour 2011 in LilleZF2 Presentation @PHP Tour 2011 in Lille
ZF2 Presentation @PHP Tour 2011 in Lille
 
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
Manage cloud infrastructures in PHP using Zend Framework 2 (and 1)
 
Cryptography with Zend Framework
Cryptography with Zend FrameworkCryptography with Zend Framework
Cryptography with Zend Framework
 
Introduction to Zend Framework
Introduction to Zend FrameworkIntroduction to Zend Framework
Introduction to Zend Framework
 
Instant ACLs with Zend Framework 2
Instant ACLs with Zend Framework 2Instant ACLs with Zend Framework 2
Instant ACLs with Zend Framework 2
 
2007 Zend Con Mvc Edited Irmantas
2007 Zend Con Mvc Edited Irmantas2007 Zend Con Mvc Edited Irmantas
2007 Zend Con Mvc Edited Irmantas
 
Extending Zend_Tool
Extending Zend_ToolExtending Zend_Tool
Extending Zend_Tool
 
Zf2 phpquebec
Zf2 phpquebecZf2 phpquebec
Zf2 phpquebec
 
How to build customizable multitenant web applications - PHPBNL11
How to build customizable multitenant web applications - PHPBNL11How to build customizable multitenant web applications - PHPBNL11
How to build customizable multitenant web applications - PHPBNL11
 
Using Zend_Tool to Establish Your Project's Skeleton
Using Zend_Tool to Establish Your Project's SkeletonUsing Zend_Tool to Establish Your Project's Skeleton
Using Zend_Tool to Establish Your Project's Skeleton
 
Testing untestable code - phpday
Testing untestable code - phpdayTesting untestable code - phpday
Testing untestable code - phpday
 
A Zend Architecture presentation
A Zend Architecture presentationA Zend Architecture presentation
A Zend Architecture presentation
 
Apigility reloaded
Apigility reloadedApigility reloaded
Apigility reloaded
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
 
Symfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friendSymfony2 Service Container: Inject me, my friend
Symfony2 Service Container: Inject me, my friend
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
 
Hierarchy Viewer Internals
Hierarchy Viewer InternalsHierarchy Viewer Internals
Hierarchy Viewer Internals
 

Ähnlich wie Zend Framework 2 quick start

Eclipse HandsOn Workshop
Eclipse HandsOn WorkshopEclipse HandsOn Workshop
Eclipse HandsOn Workshop
Bastian Feder
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & Application
Jace Ju
 

Ähnlich wie Zend Framework 2 quick start (20)

How to Manage Cloud Infrastructures using Zend Framework
How to Manage Cloud Infrastructures using Zend FrameworkHow to Manage Cloud Infrastructures using Zend Framework
How to Manage Cloud Infrastructures using Zend Framework
 
Eclipse HandsOn Workshop
Eclipse HandsOn WorkshopEclipse HandsOn Workshop
Eclipse HandsOn Workshop
 
Z ray plugins for dummies
Z ray plugins for dummiesZ ray plugins for dummies
Z ray plugins for dummies
 
Getting Native with NDK
Getting Native with NDKGetting Native with NDK
Getting Native with NDK
 
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
 
Php Development With Eclipde PDT
Php Development With Eclipde PDTPhp Development With Eclipde PDT
Php Development With Eclipde PDT
 
Configuration Management and Transforming Legacy Applications in the Enterpri...
Configuration Management and Transforming Legacy Applications in the Enterpri...Configuration Management and Transforming Legacy Applications in the Enterpri...
Configuration Management and Transforming Legacy Applications in the Enterpri...
 
Extension and Evolution
Extension and EvolutionExtension and Evolution
Extension and Evolution
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012
 
Ростислав Михайлив "Zend Framework 3 - evolution or revolution"
Ростислав Михайлив "Zend Framework 3 - evolution or revolution"Ростислав Михайлив "Zend Framework 3 - evolution or revolution"
Ростислав Михайлив "Zend Framework 3 - evolution or revolution"
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & Application
 
Php7 extensions workshop
Php7 extensions workshopPhp7 extensions workshop
Php7 extensions workshop
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
 
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
 
Eclipse Pdt2.0 26.05.2009
Eclipse Pdt2.0 26.05.2009Eclipse Pdt2.0 26.05.2009
Eclipse Pdt2.0 26.05.2009
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
 
Debugging PHP with xDebug inside of Eclipse PDT 2.1
Debugging PHP with xDebug inside of Eclipse PDT 2.1Debugging PHP with xDebug inside of Eclipse PDT 2.1
Debugging PHP with xDebug inside of Eclipse PDT 2.1
 
PHP Development Tools 2.0 - Success Story
PHP Development Tools 2.0 - Success StoryPHP Development Tools 2.0 - Success Story
PHP Development Tools 2.0 - Success Story
 
Foundations of Zend Framework
Foundations of Zend FrameworkFoundations of Zend Framework
Foundations of Zend Framework
 
Applying software engineering to configuration management
Applying software engineering to configuration managementApplying software engineering to configuration management
Applying software engineering to configuration management
 

Mehr von Enrico Zimuel

Mehr von Enrico Zimuel (20)

Password (in)security
Password (in)securityPassword (in)security
Password (in)security
 
Integrare Zend Framework in Wordpress
Integrare Zend Framework in WordpressIntegrare Zend Framework in Wordpress
Integrare Zend Framework in Wordpress
 
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecnicheIntroduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
Introduzione alla Posta Elettronica Certificata (PEC): le regole tecniche
 
PHP goes mobile
PHP goes mobilePHP goes mobile
PHP goes mobile
 
Zend Framework 2
Zend Framework 2Zend Framework 2
Zend Framework 2
 
Cryptography in PHP: use cases
Cryptography in PHP: use casesCryptography in PHP: use cases
Cryptography in PHP: use cases
 
Framework software e Zend Framework
Framework software e Zend FrameworkFramework software e Zend Framework
Framework software e Zend Framework
 
Strong cryptography in PHP
Strong cryptography in PHPStrong cryptography in PHP
Strong cryptography in PHP
 
How to scale PHP applications
How to scale PHP applicationsHow to scale PHP applications
How to scale PHP applications
 
Velocizzare Joomla! con Zend Server Community Edition
Velocizzare Joomla! con Zend Server Community EditionVelocizzare Joomla! con Zend Server Community Edition
Velocizzare Joomla! con Zend Server Community Edition
 
Zend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applicationsZend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applications
 
XCheck a benchmark checker for XML query processors
XCheck a benchmark checker for XML query processorsXCheck a benchmark checker for XML query processors
XCheck a benchmark checker for XML query processors
 
Introduzione alle tabelle hash
Introduzione alle tabelle hashIntroduzione alle tabelle hash
Introduzione alle tabelle hash
 
Crittografia quantistica: fantascienza o realtà?
Crittografia quantistica: fantascienza o realtà?Crittografia quantistica: fantascienza o realtà?
Crittografia quantistica: fantascienza o realtà?
 
Introduzione alla crittografia
Introduzione alla crittografiaIntroduzione alla crittografia
Introduzione alla crittografia
 
Crittografia è sinonimo di sicurezza?
Crittografia è sinonimo di sicurezza?Crittografia è sinonimo di sicurezza?
Crittografia è sinonimo di sicurezza?
 
Sviluppo di applicazioni sicure
Sviluppo di applicazioni sicureSviluppo di applicazioni sicure
Sviluppo di applicazioni sicure
 
Misure minime di sicurezza informatica
Misure minime di sicurezza informaticaMisure minime di sicurezza informatica
Misure minime di sicurezza informatica
 
PHP e crittografia
PHP e crittografiaPHP e crittografia
PHP e crittografia
 
La sicurezza delle applicazioni in PHP
La sicurezza delle applicazioni in PHPLa sicurezza delle applicazioni in PHP
La sicurezza delle applicazioni in PHP
 

Kürzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

Zend Framework 2 quick start

  • 1. 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.
  • 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: enrico@zend.com – Twitter: @ezimuel © All rights reserved. Zend Technologies, Inc.