SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler offline
Using ZF2 Components

     Shawn Stratton

      August 4, 2011
What is Zend Framework 2?


  • PHP 5.3 based component library (can be used as a full framework).

  • FLOSS (Modified BSD License) with Copyright License Agreement.

  • Corporate Backed by Zend Enterprises.

  • Chief Architect is Matthew Weier O‘Phinney.




                                                                         2
Why Use ZF2 Components


  • They’re new and shiny (fun to learn).

  • Natural upgrade path for ZF1.

  • Uses new PHP 5.3 features for better performance & design (newer
    fancy architecture).

  • Better quality (built from experience with ZF1).




                                                                       3
PHP 5.3 and You

There are a few things you need to know about PHP 5.3 to understand
some of the concepts in Zend Framework 2. These are:

  • Namespacing.

  • Anonymous functions and closures.

  • Late Static Binding.




                                                                      4
Namespaces


   • Common in other languages, new to PHP as of 5.3.

   • We’ve (Community) been doing it in (sort of) using underscores.

   • Just an organizational tool, denoted be backslashes.

   • Adds importing and aliasing (think .NET and Java). “use x” and “use
     x as y”

<?php
namespace Zend Session  Storage ;
use A r r a y O b j e c t ,
Zend Session  Storage ,
Zend Session  E x c e p t i o n ;
c l a s s A r r a y S t o r a g e extends A r r a y O b j e c t implements
      Storage
{ /* . . . */ }

                                                                             5
Anonymous Functions & Closures


   • Popular in Javascript.

   • Closures are the same as anonymous functions but can have access
     to parent scope elements.

<?php
$var = ’ t e s t ’ ;
/ / T h i s i s a c l o s u r e , note t h e use s t a t e m e n t
$func = f u n c t i o n ( ) use ( $var )
{
    echo $var ;
};
$func ( ) ;




                                                                        6
Late Static Binding


  • Can resolve current called class in static method.

  • Adds several functions and constants.

  • So far I haven’t seen this used in ZF2 yet, but I wouldn’t be surprised
    if it makes it into things dealing with modeling and the database.




                                                                              7
Late Static Binding cont.


<?php
class A {
    p u b l i c s t a t i c who ( ) {
        echo        CLASS ;
    }
    public static test () {
        s e l f : : who ( ) ;
        s t a t i c : : who ( ) ;
    }
}
c l a s s B extends A {
    p u b l i c s t a t i c who ( ) {
        echo        CLASS ;
    }
}



                                        8
Lets Meet The Components
List of Components for today


  • ZendLoader, New Autoloader

  • ZendDi, Dependency Injection Container

  • ZendEventManager, PubSubHub style Event Manager (more about
    what this is later)




                                                                   10
ZendLoader
ZF1 Autoloading

How does autoloading currently work in Zend Framework?

  • Works on Registered “Namespaces” such as Zend.

  • Takes classname and replaces with / in the classname and adds
    .php to the end.

  • Checks the include path for the filename it comes up with, if it exists
    include it.

  • Similar to other “1st generation” framework autoloaders.

  • Can add other “Namespaces”.




                                                                             12
ZF1 Autoloading Example


<?php
require once         Z e n d / Loader / S t a n d a r d A u t o l o a d e r . p h p    ;
$ l o a d e r = new Zend Loader  S t a n d a r d A u t o l o a d e r ( a r r a y (
   fallback autoloader              => t r u e ,
));
$loader −>r e g i s t e r ( ) ;




                                                                                           13
So what’s different in ZF2


  • Different types of autoloaders (Classmap, PSR0, prefix/namespace
    specific autoloading)

  • Can chain “fallback” autoloaders

  • Higher performance due to direct requests

  • ZF2 no longer uses require once statements in the source files




                                                                      14
ZF2 Namespace Prefix Autoloading


<?php
require once               Z e n d / Loader / S t a n d a r d A u t o l o a d e r . p h p   ;
$ l o a d e r = new Zend Loader  S t a n d a r d A u t o l o a d e r ( ) ;
$loader −>registerNamespace (                   My          ,      DIR          .
            / . . / library / M y )
−>r e g i s t e r P r e f i x ( P h l y       ,      DIR         .
            / . . / library / P h l y ) ;
$loader −>r e g i s t e r ( ) ;




                                                                                                15
ZF2 Class-Map Autoloading


<?PHP
$map = a r r a y (
    M y Foo B a r        =>     DIR      .      / Foo / Bar . p h p   ,
);

require once                 Z e n d / Loader / ClassMapAutoloader . p h p   ;
$ l o a d e r = new Zend Loader  ClassMapAutoloader ( ) ;
$loader −>r e g i s t e r A u t o l o a d M a p ( D I R    .
            / . . / l i b r a r y / . classmap . p h p ) ;
$loader −>r e g i s t e r ( ) ;




                                                                                 16
More about ZF2 Class-Map Autoloading


  • Yes you will need to create classmaps,

  • ZF2 has a tool to generate these for you.

  • Shows significant performance improvement over “include path”
    autoloaders.

  • According to the Supreme Allied Commander (Matthew Weier
    O‘Phiney) Class-Maps show a 25% speed improvement over ZF1
    Autoloader and a 60% to 85% improvement with a opcode cache
    enabled.




                                                                   17
Factory

ZendLoader also has a factory that will allow you to quickly assemble
your autoloading strategy and implement it.
<?php
require once          Z e n d / Loader / A u t o l o a d e r F a c t o r y . p h p   ;
use Zend Loader  A u t o l o a d e r F a c t o r y ;
AutoloaderFactory : : f a c t o r y ( array (
  Z e n d  Loader  C l a s s M a p A u t o l o a d e r => a r r a y (
   DIR      .      / . . / l i b r a r y / . classmap . p h p ,
   DIR      .      / . . / a p p l i c a t i o n / . classmap . p h p ,
),
  Z e n d  Loader  S t a n d a r d A u t o l o a d e r => a r r a y (
  n a m e s p a c e s => a r r a y (
   Zend         =>      DIR          .          / . . / library / Zend ,
),
  fallback autoloader                        => t r u e ,
),
));
                                                                                         18
So what are we doing with HowStuffWorks.com


  • Well as of right now we still do require/include once statements,
    mostly for performance reasons.




                                                                        19
So what are we doing with HowStuffWorks.com


  • Well as of right now we still do require/include once statements,
    mostly for performance reasons.

  • We’ve tested ZF2 Class Map autoloading with the PSR0 Fallback
    using APC and saw 20% performance increase (approx 40ms on the
    front-end.)




                                                                        19
So what are we doing with HowStuffWorks.com


  • Well as of right now we still do require/include once statements,
    mostly for performance reasons.

  • We’ve tested ZF2 Class Map autoloading with the PSR0 Fallback
    using APC and saw 20% performance increase (approx 40ms on the
    front-end.)

  • Not in production yet but it is on our roadmap (we have a large code
    base and it’ll take some time to adapt it all and test it).




                                                                           19
Oh Just a Side Note


  • Matthew Weier O‘Phinney has already taken the liberty to package
    the ZF2 autoloader as a PHP 5.2 compliant package, you can get it
    http://bit.ly/zf2autoloadfor52




                                                                        20
Oh Just a Side Note


  • Matthew Weier O‘Phinney has already taken the liberty to package
    the ZF2 autoloader as a PHP 5.2 compliant package, you can get it
    http://bit.ly/zf2autoloadfor52

  • I’ve ported this into the ZendX namespace in a PHP 5.3 compliant
    package, find me later and I’ll get you a copy




                                                                        20
ZendDi
What is DI?


  • Dependency Injection is just a Construction / Design Pattern,
    previously discussed (last month actually).

  • Pattern outlines that all Dependencies should be passed into an
    object rather than “retrieved” by said object.

  • Allows for more flexibility and better testing.

  • In this case it’s a Dependency Injection Container.

  • Again it’s just a fancy registry.




                                                                      22
What is ZendDi for?


  • ZF2 is planning on using Dependency Injection with it’s Controllers
    and for provided Services.

  • Most of the library components do use Dependency Injection as their
    design pattern.

  • ZendDi is a construction helper, everything in ZF2 thus far can run
    without the DI Container (maybe not the locater).




                                                                           23
Some Details about ZendDi


  • Uses dependency maps to do injections.

  • These maps can be in php, ini, or xml format (ZendConfig)

  • Supports Setter Injection & Lazy Initialization instead of just
    Constructor Injection.

  • May support Dynamic Resolution of Dependencies in the future
    (Reflection)

  • The container, last I tested, was a bit heavy but I know improvements
    were being made.




                                                                            24
DI Configuration & Locater Example


<?php
use Zend Di  D e f i n i t i o n ,
    Zend Di  Reference ,
    Zend Di  D e p e n d e n c y I n j e c t o r as DI ;

$db = new D e f i n i t i o n ( ’MyDb Adapter  S q l i t e ’ ) ;
$db−>setParam ( ’ name ’ ,              DIR      .
      ’ / . . / data / db / users . db ’ ) ;
$mapper = new D e f i n i t i o n ( ’MyMapperDb ’ ) ;
$mapper−>addMethodCall ( ’ s e t A d a p t e r ’ , a r r a y ( new
     Reference ( ’ db ’ ) ) ) ;
$ s e r v i c e = new D e f i n i t i o n ( ’My Resource  Users ’ ) ;
$ s e r v i c e −>setParam ( ’ mapper ’ , new Reference ( ’ mapper ’ ) ) ;

$ d i = new DI ;
$di−>s e t D e f i n i t i o n s ( a r r a y ( ’ db ’=> $db , ’ mapper ’ =>
     $mapper , ’ users ’=> $ s e r v i c e ) ) ;
$users = $di−>g e t ( ’ users ’ ) ; / / My Resource  Users
                                                                              25
Setting Injection Example


<?php
use Zend Di  D e f i n i t i o n ,
    Zend Di  Reference ;

$ s e r v i c e = new D e f i n i t i o n ( ’mwop S e r v i c e  Resources ’ ) ;
$ s e r v i c e −>addMethod ( ’ setResource ’ , a r r a y (
       new Reference ( ’ r e s o u r c e ’ )
));

$di−>s e t D e f i n i t i o n ( ’ r e s o u r c e s ’ , $ s e r v i c e ) ;

$resources = $di−>g e t ( ’ r e s o u r c e s ’ ) ;




                                                                                     26
Considerations for ZF1 usage


  • ZF1 does not play well with Dependency Injection with it’s
    components.

  • The majority of configuration options require arrays and there is
    some differing structure for these arrays.

  • Controllers require an inherited constructor (which is why most of the
    initialization is done in init() )

  • Still works good for Service Containers and Data Models




                                                                             27
ZendEventManager
What is the EventManager?


  • A solution for providing Aspect Oriented Programing principles in
    PHP, (crosscutting concerns).

  • A combination of subject/observer pattern, PubSubHub, and Signal
    Slots? (wtf is all this?)

  • A better way of notifying other parts of the system that an event is
    about to occur/has occured with filters so that we can interact on the
    event.




                                                                            29
But why does that matter?


  • Allows for handling events without modifying/overwriting framework
    code.

  • Allows you to create hook points for other parts of the system to
    interact with at runtime.

  • It’s a major evolutionary step to Programing Philosophy (ask me
    more on Aspect Oriented Programing later if you’re interested)




                                                                         30
EventCollection Interface


<?php
namespace Zend EventManager ;
use Zend S t d l i b  C a l l b a c k H a n d l e r ;

interface EventCollection
{
    p u b l i c f u n c t i o n t r i g g e r ( $event , $ c o n t e x t , $argv =
         array ( ) ) ;
    p u b l i c f u n c t i o n t r i g g e r U n t i l ( $event , $ c o n t e x t ,
         $argv , $ c a l l b a c k ) ;
    p u b l i c f u n c t i o n a t t a c h ( $event , $ c a l l b a c k ,
         $ p r i o r i t y = 1) ;
    p u b l i c f u n c t i o n detach ( C a l l b a c k H a n d l e r $handle ) ;
    p u b l i c f u n c t i o n getEvents ( ) ;
    p u b l i c f u n c t i o n g e t H a n d l e r s ( $event ) ;
    p u b l i c f u n c t i o n c l e a r H a n d l e r s ( $event ) ;
}
                                                                                       31
Triggering Events


<?php
use Zend EventManager  EventManager ;

$events = new EventManager ( ) ;
$events−>t r i g g e r ( $eventName , $ o b j e c t , $params ) ;
/ * Where :
  * − $eventName i s t h e name o f t h e event ; u s u a l l y t h e
     current
  *   method name
  * − $ o b j e c t i s t h e o b j e c t t r i g g e r i n g t h e event
  * − $params are t h e parameters t h e h a n d l e r might
     need t o access ,
  *   u s u a l l y t h e method arguments
  */




                                                                            32
Zend Components as of ZF2
Just a quick List


  • Acl              • Controller     • File
  • Amf              • Crypt
                                      • Filter
  • Application      • Currency
                                      • Form
  • Authentication   • Date
  • Barcode          • Db             • GData

  • Cache            • Debug          • Http
  • Captcha          • Di
                                      • InfoCard
  • Code             • Dojo
  • CodeGenerator    • Dom            • Json

  • Config            • EventManager   • ProgressBar
  • Console          • Feed
                                                      34
Just a quick list, cont.


   • Layout           • Mvc          • Search     • Translator
   • Ldap             • Navigation   • Service
                                                  • Uri
   • Loader           • OAuth        • Session
                                                  • Validator
   • Locale           • OpenId       • Soap
   • Log              • Paginator    • Stdlib     • Version
   • Mail             • Pdf          • Tag
                                                  • View
   • Markup           • Queue        • Test
                                                  • Wildfire
   • Meassure         • Reflection    • Text
   • Memory           • Registry     • TimeSync   • XmlRpc
   • Mime             • Rest         • Tool


                                                                 35
There are a bunch of components out
    there, choose what you want
How To Convert for PHP 5.2
Let’s be realistic

Not all components are convertible, if they require the following
components, PHP 5.2 will not run these:

   • Closures (Anonymous Functions)

   • Late Static Binding

   • Garbage Collection




                                                                    38
Figuring out Dependencies

With PHP 5.3’s namespace aliasing, mapping dependencies actually
becomes really easy; use statements at the beginning of the file will
usually tell you what components you need from outside of that
namespace.




                                                                       39
Converting Namespaces

Some sticking points:

  • It’s easy to replace the namespace separator with the ZF1 but be
    sure to find and replace aliases.

  • It may be worth renaming the namespace from Zend to ZendX if
    using Zend Framework 1 to keep from mixing up components.

  • Be sure you remove all references to namespace, use, as, and 
    from the code, PHP 5.2 will barf on these.




                                                                       40
Conclusions


  • ZF2 Components are awesome, we can use them in ZF1 Projects
    (with a little work).

  • ZF2 Components have benefits, performance being one, shininess
    being two.

  • Integration ZF2 Components now will make refactoring to use ZF2
    later easier.

  • Why Not? The idea behind Zend Framework is to make reusable
    components (it’s technically a library not a framework), don’t get
    stuck on legacy library components just because you can’t upgrade
    your whole stack.




                                                                         41
Questions?
Thank You

Thank you for attending and a special thank you to Matthew Weier
O‘Phinney for letting me use part of his slide stack (especially source
code) from his ZF2 Patterns talk.




                                                                          43

Mais conteúdo relacionado

Mais procurados

PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
Nick Belhomme
 
Writing php extensions in golang
Writing php extensions in golangWriting php extensions in golang
Writing php extensions in golang
do_aki
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
King Foo
 

Mais procurados (20)

Zend Framework Introduction
Zend Framework IntroductionZend Framework Introduction
Zend Framework Introduction
 
PHP 7 Crash Course - php[world] 2015
PHP 7 Crash Course - php[world] 2015PHP 7 Crash Course - php[world] 2015
PHP 7 Crash Course - php[world] 2015
 
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
 
Continuous Quality Assurance
Continuous Quality AssuranceContinuous Quality Assurance
Continuous Quality Assurance
 
Zend expressive workshop
Zend expressive workshopZend expressive workshop
Zend expressive workshop
 
Mastering Namespaces in PHP
Mastering Namespaces in PHPMastering Namespaces in PHP
Mastering Namespaces in PHP
 
Apigility reloaded
Apigility reloadedApigility reloaded
Apigility reloaded
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
Writing php extensions in golang
Writing php extensions in golangWriting php extensions in golang
Writing php extensions in golang
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
 
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Doctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPDoctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHP
 
IPC 2015 ZF2rapid
IPC 2015 ZF2rapidIPC 2015 ZF2rapid
IPC 2015 ZF2rapid
 
You suck at Memory Analysis
You suck at Memory AnalysisYou suck at Memory Analysis
You suck at Memory Analysis
 
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)
 
Zephir - A Wind of Change for writing PHP extensions
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
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash Course
 
Zend Framework 2 Patterns
Zend Framework 2 PatternsZend Framework 2 Patterns
Zend Framework 2 Patterns
 

Semelhante a Zend Framework 2 Components

Getting started-with-zend-framework
Getting started-with-zend-frameworkGetting started-with-zend-framework
Getting started-with-zend-framework
Marcelo da Rocha
 
Zend con practical-zf1-zf2-migration
Zend con practical-zf1-zf2-migrationZend con practical-zf1-zf2-migration
Zend con practical-zf1-zf2-migration
Clark Everetts
 
Zend Framework 2, What's new, Confoo 2011
Zend Framework 2, What's new, Confoo 2011Zend Framework 2, What's new, Confoo 2011
Zend Framework 2, What's new, Confoo 2011
Bachkoutou Toutou
 

Semelhante a Zend Framework 2 Components (20)

Performance tuning with zend framework
Performance tuning with zend frameworkPerformance tuning with zend framework
Performance tuning with zend framework
 
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
 
Sunshine php practical-zf1-zf2-migration
Sunshine php practical-zf1-zf2-migrationSunshine php practical-zf1-zf2-migration
Sunshine php practical-zf1-zf2-migration
 
Php7 extensions workshop
Php7 extensions workshopPhp7 extensions workshop
Php7 extensions workshop
 
Getting started-with-zend-framework
Getting started-with-zend-frameworkGetting started-with-zend-framework
Getting started-with-zend-framework
 
Zend con practical-zf1-zf2-migration
Zend con practical-zf1-zf2-migrationZend con practical-zf1-zf2-migration
Zend con practical-zf1-zf2-migration
 
Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8Ran Mizrahi - Symfony2 meets Drupal8
Ran Mizrahi - Symfony2 meets Drupal8
 
Php through the eyes of a hoster confoo
Php through the eyes of a hoster confooPhp through the eyes of a hoster confoo
Php through the eyes of a hoster confoo
 
Zend Framework 2, What's new, Confoo 2011
Zend Framework 2, What's new, Confoo 2011Zend Framework 2, What's new, Confoo 2011
Zend Framework 2, What's new, Confoo 2011
 
Composer Helpdesk
Composer HelpdeskComposer Helpdesk
Composer Helpdesk
 
Php through the eyes of a hoster
Php through the eyes of a hosterPhp through the eyes of a hoster
Php through the eyes of a hoster
 
Get your teeth into Plack
Get your teeth into PlackGet your teeth into Plack
Get your teeth into Plack
 
DevOps in PHP environment
DevOps in PHP environment DevOps in PHP environment
DevOps in PHP environment
 
Z-Ray: A customizable development tool belt (Zendcon 2016)
Z-Ray: A customizable development tool belt (Zendcon 2016)Z-Ray: A customizable development tool belt (Zendcon 2016)
Z-Ray: A customizable development tool belt (Zendcon 2016)
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Extending ZF & Extending With ZF
Extending ZF & Extending With ZFExtending ZF & Extending With ZF
Extending ZF & Extending With ZF
 
Fabric - a server management tool from Instagram
Fabric - a server management tool from InstagramFabric - a server management tool from Instagram
Fabric - a server management tool from Instagram
 
The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6
 
Zend Code in ZF 2.0
Zend Code in ZF 2.0Zend Code in ZF 2.0
Zend Code in ZF 2.0
 
Php extensions
Php extensionsPhp extensions
Php extensions
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Zend Framework 2 Components

  • 1. Using ZF2 Components Shawn Stratton August 4, 2011
  • 2. What is Zend Framework 2? • PHP 5.3 based component library (can be used as a full framework). • FLOSS (Modified BSD License) with Copyright License Agreement. • Corporate Backed by Zend Enterprises. • Chief Architect is Matthew Weier O‘Phinney. 2
  • 3. Why Use ZF2 Components • They’re new and shiny (fun to learn). • Natural upgrade path for ZF1. • Uses new PHP 5.3 features for better performance & design (newer fancy architecture). • Better quality (built from experience with ZF1). 3
  • 4. PHP 5.3 and You There are a few things you need to know about PHP 5.3 to understand some of the concepts in Zend Framework 2. These are: • Namespacing. • Anonymous functions and closures. • Late Static Binding. 4
  • 5. Namespaces • Common in other languages, new to PHP as of 5.3. • We’ve (Community) been doing it in (sort of) using underscores. • Just an organizational tool, denoted be backslashes. • Adds importing and aliasing (think .NET and Java). “use x” and “use x as y” <?php namespace Zend Session Storage ; use A r r a y O b j e c t , Zend Session Storage , Zend Session E x c e p t i o n ; c l a s s A r r a y S t o r a g e extends A r r a y O b j e c t implements Storage { /* . . . */ } 5
  • 6. Anonymous Functions & Closures • Popular in Javascript. • Closures are the same as anonymous functions but can have access to parent scope elements. <?php $var = ’ t e s t ’ ; / / T h i s i s a c l o s u r e , note t h e use s t a t e m e n t $func = f u n c t i o n ( ) use ( $var ) { echo $var ; }; $func ( ) ; 6
  • 7. Late Static Binding • Can resolve current called class in static method. • Adds several functions and constants. • So far I haven’t seen this used in ZF2 yet, but I wouldn’t be surprised if it makes it into things dealing with modeling and the database. 7
  • 8. Late Static Binding cont. <?php class A { p u b l i c s t a t i c who ( ) { echo CLASS ; } public static test () { s e l f : : who ( ) ; s t a t i c : : who ( ) ; } } c l a s s B extends A { p u b l i c s t a t i c who ( ) { echo CLASS ; } } 8
  • 9. Lets Meet The Components
  • 10. List of Components for today • ZendLoader, New Autoloader • ZendDi, Dependency Injection Container • ZendEventManager, PubSubHub style Event Manager (more about what this is later) 10
  • 12. ZF1 Autoloading How does autoloading currently work in Zend Framework? • Works on Registered “Namespaces” such as Zend. • Takes classname and replaces with / in the classname and adds .php to the end. • Checks the include path for the filename it comes up with, if it exists include it. • Similar to other “1st generation” framework autoloaders. • Can add other “Namespaces”. 12
  • 13. ZF1 Autoloading Example <?php require once Z e n d / Loader / S t a n d a r d A u t o l o a d e r . p h p ; $ l o a d e r = new Zend Loader S t a n d a r d A u t o l o a d e r ( a r r a y ( fallback autoloader => t r u e , )); $loader −>r e g i s t e r ( ) ; 13
  • 14. So what’s different in ZF2 • Different types of autoloaders (Classmap, PSR0, prefix/namespace specific autoloading) • Can chain “fallback” autoloaders • Higher performance due to direct requests • ZF2 no longer uses require once statements in the source files 14
  • 15. ZF2 Namespace Prefix Autoloading <?php require once Z e n d / Loader / S t a n d a r d A u t o l o a d e r . p h p ; $ l o a d e r = new Zend Loader S t a n d a r d A u t o l o a d e r ( ) ; $loader −>registerNamespace ( My , DIR . / . . / library / M y ) −>r e g i s t e r P r e f i x ( P h l y , DIR . / . . / library / P h l y ) ; $loader −>r e g i s t e r ( ) ; 15
  • 16. ZF2 Class-Map Autoloading <?PHP $map = a r r a y ( M y Foo B a r => DIR . / Foo / Bar . p h p , ); require once Z e n d / Loader / ClassMapAutoloader . p h p ; $ l o a d e r = new Zend Loader ClassMapAutoloader ( ) ; $loader −>r e g i s t e r A u t o l o a d M a p ( D I R . / . . / l i b r a r y / . classmap . p h p ) ; $loader −>r e g i s t e r ( ) ; 16
  • 17. More about ZF2 Class-Map Autoloading • Yes you will need to create classmaps, • ZF2 has a tool to generate these for you. • Shows significant performance improvement over “include path” autoloaders. • According to the Supreme Allied Commander (Matthew Weier O‘Phiney) Class-Maps show a 25% speed improvement over ZF1 Autoloader and a 60% to 85% improvement with a opcode cache enabled. 17
  • 18. Factory ZendLoader also has a factory that will allow you to quickly assemble your autoloading strategy and implement it. <?php require once Z e n d / Loader / A u t o l o a d e r F a c t o r y . p h p ; use Zend Loader A u t o l o a d e r F a c t o r y ; AutoloaderFactory : : f a c t o r y ( array ( Z e n d Loader C l a s s M a p A u t o l o a d e r => a r r a y ( DIR . / . . / l i b r a r y / . classmap . p h p , DIR . / . . / a p p l i c a t i o n / . classmap . p h p , ), Z e n d Loader S t a n d a r d A u t o l o a d e r => a r r a y ( n a m e s p a c e s => a r r a y ( Zend => DIR . / . . / library / Zend , ), fallback autoloader => t r u e , ), )); 18
  • 19. So what are we doing with HowStuffWorks.com • Well as of right now we still do require/include once statements, mostly for performance reasons. 19
  • 20. So what are we doing with HowStuffWorks.com • Well as of right now we still do require/include once statements, mostly for performance reasons. • We’ve tested ZF2 Class Map autoloading with the PSR0 Fallback using APC and saw 20% performance increase (approx 40ms on the front-end.) 19
  • 21. So what are we doing with HowStuffWorks.com • Well as of right now we still do require/include once statements, mostly for performance reasons. • We’ve tested ZF2 Class Map autoloading with the PSR0 Fallback using APC and saw 20% performance increase (approx 40ms on the front-end.) • Not in production yet but it is on our roadmap (we have a large code base and it’ll take some time to adapt it all and test it). 19
  • 22. Oh Just a Side Note • Matthew Weier O‘Phinney has already taken the liberty to package the ZF2 autoloader as a PHP 5.2 compliant package, you can get it http://bit.ly/zf2autoloadfor52 20
  • 23. Oh Just a Side Note • Matthew Weier O‘Phinney has already taken the liberty to package the ZF2 autoloader as a PHP 5.2 compliant package, you can get it http://bit.ly/zf2autoloadfor52 • I’ve ported this into the ZendX namespace in a PHP 5.3 compliant package, find me later and I’ll get you a copy 20
  • 25. What is DI? • Dependency Injection is just a Construction / Design Pattern, previously discussed (last month actually). • Pattern outlines that all Dependencies should be passed into an object rather than “retrieved” by said object. • Allows for more flexibility and better testing. • In this case it’s a Dependency Injection Container. • Again it’s just a fancy registry. 22
  • 26. What is ZendDi for? • ZF2 is planning on using Dependency Injection with it’s Controllers and for provided Services. • Most of the library components do use Dependency Injection as their design pattern. • ZendDi is a construction helper, everything in ZF2 thus far can run without the DI Container (maybe not the locater). 23
  • 27. Some Details about ZendDi • Uses dependency maps to do injections. • These maps can be in php, ini, or xml format (ZendConfig) • Supports Setter Injection & Lazy Initialization instead of just Constructor Injection. • May support Dynamic Resolution of Dependencies in the future (Reflection) • The container, last I tested, was a bit heavy but I know improvements were being made. 24
  • 28. DI Configuration & Locater Example <?php use Zend Di D e f i n i t i o n , Zend Di Reference , Zend Di D e p e n d e n c y I n j e c t o r as DI ; $db = new D e f i n i t i o n ( ’MyDb Adapter S q l i t e ’ ) ; $db−>setParam ( ’ name ’ , DIR . ’ / . . / data / db / users . db ’ ) ; $mapper = new D e f i n i t i o n ( ’MyMapperDb ’ ) ; $mapper−>addMethodCall ( ’ s e t A d a p t e r ’ , a r r a y ( new Reference ( ’ db ’ ) ) ) ; $ s e r v i c e = new D e f i n i t i o n ( ’My Resource Users ’ ) ; $ s e r v i c e −>setParam ( ’ mapper ’ , new Reference ( ’ mapper ’ ) ) ; $ d i = new DI ; $di−>s e t D e f i n i t i o n s ( a r r a y ( ’ db ’=> $db , ’ mapper ’ => $mapper , ’ users ’=> $ s e r v i c e ) ) ; $users = $di−>g e t ( ’ users ’ ) ; / / My Resource Users 25
  • 29. Setting Injection Example <?php use Zend Di D e f i n i t i o n , Zend Di Reference ; $ s e r v i c e = new D e f i n i t i o n ( ’mwop S e r v i c e Resources ’ ) ; $ s e r v i c e −>addMethod ( ’ setResource ’ , a r r a y ( new Reference ( ’ r e s o u r c e ’ ) )); $di−>s e t D e f i n i t i o n ( ’ r e s o u r c e s ’ , $ s e r v i c e ) ; $resources = $di−>g e t ( ’ r e s o u r c e s ’ ) ; 26
  • 30. Considerations for ZF1 usage • ZF1 does not play well with Dependency Injection with it’s components. • The majority of configuration options require arrays and there is some differing structure for these arrays. • Controllers require an inherited constructor (which is why most of the initialization is done in init() ) • Still works good for Service Containers and Data Models 27
  • 32. What is the EventManager? • A solution for providing Aspect Oriented Programing principles in PHP, (crosscutting concerns). • A combination of subject/observer pattern, PubSubHub, and Signal Slots? (wtf is all this?) • A better way of notifying other parts of the system that an event is about to occur/has occured with filters so that we can interact on the event. 29
  • 33. But why does that matter? • Allows for handling events without modifying/overwriting framework code. • Allows you to create hook points for other parts of the system to interact with at runtime. • It’s a major evolutionary step to Programing Philosophy (ask me more on Aspect Oriented Programing later if you’re interested) 30
  • 34. EventCollection Interface <?php namespace Zend EventManager ; use Zend S t d l i b C a l l b a c k H a n d l e r ; interface EventCollection { p u b l i c f u n c t i o n t r i g g e r ( $event , $ c o n t e x t , $argv = array ( ) ) ; p u b l i c f u n c t i o n t r i g g e r U n t i l ( $event , $ c o n t e x t , $argv , $ c a l l b a c k ) ; p u b l i c f u n c t i o n a t t a c h ( $event , $ c a l l b a c k , $ p r i o r i t y = 1) ; p u b l i c f u n c t i o n detach ( C a l l b a c k H a n d l e r $handle ) ; p u b l i c f u n c t i o n getEvents ( ) ; p u b l i c f u n c t i o n g e t H a n d l e r s ( $event ) ; p u b l i c f u n c t i o n c l e a r H a n d l e r s ( $event ) ; } 31
  • 35. Triggering Events <?php use Zend EventManager EventManager ; $events = new EventManager ( ) ; $events−>t r i g g e r ( $eventName , $ o b j e c t , $params ) ; / * Where : * − $eventName i s t h e name o f t h e event ; u s u a l l y t h e current * method name * − $ o b j e c t i s t h e o b j e c t t r i g g e r i n g t h e event * − $params are t h e parameters t h e h a n d l e r might need t o access , * u s u a l l y t h e method arguments */ 32
  • 37. Just a quick List • Acl • Controller • File • Amf • Crypt • Filter • Application • Currency • Form • Authentication • Date • Barcode • Db • GData • Cache • Debug • Http • Captcha • Di • InfoCard • Code • Dojo • CodeGenerator • Dom • Json • Config • EventManager • ProgressBar • Console • Feed 34
  • 38. Just a quick list, cont. • Layout • Mvc • Search • Translator • Ldap • Navigation • Service • Uri • Loader • OAuth • Session • Validator • Locale • OpenId • Soap • Log • Paginator • Stdlib • Version • Mail • Pdf • Tag • View • Markup • Queue • Test • Wildfire • Meassure • Reflection • Text • Memory • Registry • TimeSync • XmlRpc • Mime • Rest • Tool 35
  • 39. There are a bunch of components out there, choose what you want
  • 40. How To Convert for PHP 5.2
  • 41. Let’s be realistic Not all components are convertible, if they require the following components, PHP 5.2 will not run these: • Closures (Anonymous Functions) • Late Static Binding • Garbage Collection 38
  • 42. Figuring out Dependencies With PHP 5.3’s namespace aliasing, mapping dependencies actually becomes really easy; use statements at the beginning of the file will usually tell you what components you need from outside of that namespace. 39
  • 43. Converting Namespaces Some sticking points: • It’s easy to replace the namespace separator with the ZF1 but be sure to find and replace aliases. • It may be worth renaming the namespace from Zend to ZendX if using Zend Framework 1 to keep from mixing up components. • Be sure you remove all references to namespace, use, as, and from the code, PHP 5.2 will barf on these. 40
  • 44. Conclusions • ZF2 Components are awesome, we can use them in ZF1 Projects (with a little work). • ZF2 Components have benefits, performance being one, shininess being two. • Integration ZF2 Components now will make refactoring to use ZF2 later easier. • Why Not? The idea behind Zend Framework is to make reusable components (it’s technically a library not a framework), don’t get stuck on legacy library components just because you can’t upgrade your whole stack. 41
  • 46. Thank You Thank you for attending and a special thank you to Matthew Weier O‘Phinney for letting me use part of his slide stack (especially source code) from his ZF2 Patterns talk. 43