46
Using ZF2 Components Shawn Stratton August 4, 2011

Zend Framework 2 Components

Embed Size (px)

DESCRIPTION

Atlanta

Citation preview

Page 1: Zend Framework 2 Components

Using ZF2 Components

Shawn Stratton

August 4, 2011

Page 2: Zend Framework 2 Components

What is Zend Framework 2?

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.

Page 3: Zend Framework 2 Components

Why Use ZF2 Components

3

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

• Natural upgrade path for ZF1.

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

• Better quality (built from experience with ZF1).

Page 4: Zend Framework 2 Components

PHP 5.3 and You

4

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

• Namespacing.

• Anonymous functions and closures.

• Late Static Binding.

Page 5: Zend Framework 2 Components

Namespaces

5

• 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 “usex as y”

<?phpnamespace Zend\Session\Storage ;use ArrayObject ,Zend\Session\Storage ,Zend\Session\Except ion ;c lass ArrayStorage extends ArrayObject implements

Storage{ / * . . . * / }

Page 6: Zend Framework 2 Components

Anonymous Functions & Closures

6

• Popular in Javascript.

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

<?php$var = ’ t e s t ’ ;/ / This i s a c losure , note the use statement$func = f u n c t i o n ( ) use ( $var ){

echo $var ;} ;$func ( ) ;

Page 7: Zend Framework 2 Components

Late Static Binding

7

• 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 surprisedif it makes it into things dealing with modeling and the database.

Page 8: Zend Framework 2 Components

Late Static Binding cont.

8

<?phpc lass A {

p u b l i c s t a t i c who ( ) {echo CLASS ;

}p u b l i c s t a t i c t e s t ( ) {

s e l f : : who ( ) ;s t a t i c : : who ( ) ;

}}c lass B extends A {

p u b l i c s t a t i c who ( ) {echo CLASS ;

}}

Page 9: Zend Framework 2 Components

Lets Meet The Components

Page 10: Zend Framework 2 Components

List of Components for today

10

• Zend\Loader, New Autoloader

• Zend\Di, Dependency Injection Container

• Zend\EventManager, PubSubHub style Event Manager (more aboutwhat this is later)

Page 11: Zend Framework 2 Components

Zend\Loader

Page 12: Zend Framework 2 Components

ZF1 Autoloading

12

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 existsinclude it.

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

• Can add other “Namespaces”.

Page 13: Zend Framework 2 Components

ZF1 Autoloading Example

13

<?phprequ i re once Z e n d / Loader / StandardAutoloader . p h p ;$ loader = new Zend\Loader\StandardAutoloader ( ar ray (

f a l l b a c k a u t o l o a d e r => t rue ,) ) ;$loader−>r e g i s t e r ( ) ;

Page 14: Zend Framework 2 Components

So what’s different in ZF2

14

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

• Can chain “fallback” autoloaders

• Higher performance due to direct requests

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

Page 15: Zend Framework 2 Components

ZF2 Namespace Prefix Autoloading

15

<?phprequ i re once Z e n d / Loader / StandardAutoloader . p h p ;$ loader = new Zend\Loader\StandardAutoloader ( ) ;$loader−>registerNamespace ( M y , D IR .

/ . . / l i b r a r y / M y )−>r e g i s t e r P r e f i x ( P h l y , D IR .

/ . . / l i b r a r y / P h l y ) ;$loader−>r e g i s t e r ( ) ;

Page 16: Zend Framework 2 Components

ZF2 Class-Map Autoloading

16

<?PHP$map = ar ray (

M y \Foo\ B a r => DIR . / Foo / Bar . p h p ,) ;

requ i re once Z e n d / Loader / ClassMapAutoloader . p h p ;$ loader = new Zend\Loader\ClassMapAutoloader ( ) ;$loader−>reg is terAuto loadMap ( DIR .

/ . . / l i b r a r y / . classmap . p h p ) ;$loader−>r e g i s t e r ( ) ;

Page 17: Zend Framework 2 Components

More about ZF2 Class-Map Autoloading

17

• 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 WeierO‘Phiney) Class-Maps show a 25% speed improvement over ZF1Autoloader and a 60% to 85% improvement with a opcode cacheenabled.

Page 18: Zend Framework 2 Components

Factory

18

Zend\Loader also has a factory that will allow you to quickly assembleyour autoloading strategy and implement it.

<?phprequ i re once Z e n d / Loader / Auto loaderFactory . p h p ;use Zend\Loader\Auto loaderFactory ;Auto loaderFactory : : f a c t o r y ( ar ray (

Z e n d \Loader\ C l a s s M a p A u t o l o a d e r => ar ray (D IR . / . . / l i b r a r y / . classmap . p h p ,D IR . / . . / 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 => ar ray (n a m e s p a c e s => ar ray (Z e n d => DIR . / . . / l i b r a r y / Z e n d ,

) ,f a l l b a c k a u t o l o a d e r => t rue ,

) ,) ) ;

Page 19: Zend Framework 2 Components

So what are we doing with HowStuffWorks.com

19

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

Page 20: Zend Framework 2 Components

So what are we doing with HowStuffWorks.com

19

• 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 Fallbackusing APC and saw 20% performance increase (approx 40ms on thefront-end.)

Page 21: Zend Framework 2 Components

So what are we doing with HowStuffWorks.com

19

• 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 Fallbackusing APC and saw 20% performance increase (approx 40ms on thefront-end.)

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

Page 22: Zend Framework 2 Components

Oh Just a Side Note

20

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

Page 23: Zend Framework 2 Components

Oh Just a Side Note

20

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

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

Page 24: Zend Framework 2 Components

Zend\Di

Page 25: Zend Framework 2 Components

What is DI?

22

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

• Pattern outlines that all Dependencies should be passed into anobject 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.

Page 26: Zend Framework 2 Components

What is Zend \Di for?

23

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

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

• Zend\Di is a construction helper, everything in ZF2 thus far can runwithout the DI Container (maybe not the locater).

Page 27: Zend Framework 2 Components

Some Details about Zend \Di

24

• Uses dependency maps to do injections.

• These maps can be in php, ini, or xml format (Zend\Config)

• Supports Setter Injection & Lazy Initialization instead of justConstructor Injection.

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

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

Page 28: Zend Framework 2 Components

DI Configuration & Locater Example

25

<?phpuse Zend\Di\ D e f i n i t i o n ,

Zend\Di\Reference ,Zend\Di\DependencyInjector as DI ;

$db = new D e f i n i t i o n ( ’My\Db\Adapter\ S q l i t e ’ ) ;$db−>setParam ( ’name ’ , D IR .

’ / . . / data / db / users . db ’ ) ;$mapper = new D e f i n i t i o n ( ’My\Mapper\Db ’ ) ;$mapper−>addMethodCall ( ’ setAdapter ’ , a r ray (new

Reference ( ’ db ’ ) ) ) ;$serv ice = new D e f i n i t i o n ( ’My\Resource\Users ’ ) ;$serv ice−>setParam ( ’ mapper ’ , new Reference ( ’ mapper ’ ) ) ;

$d i = new DI ;$di−>s e t D e f i n i t i o n s ( ar ray ( ’ db ’=> $db , ’ mapper ’ =>

$mapper , ’ users ’=> $serv ice ) ) ;$users = $di−>get ( ’ users ’ ) ; / / My\Resource\Users

Page 29: Zend Framework 2 Components

Setting Injection Example

26

<?phpuse Zend\Di\ D e f i n i t i o n ,

Zend\Di\Reference ;

$serv ice = new D e f i n i t i o n ( ’mwop\Serv ice \Resources ’ ) ;$serv ice−>addMethod ( ’ setResource ’ , a r ray (

new Reference ( ’ resource ’ )) ) ;

$di−>s e t D e f i n i t i o n ( ’ resources ’ , $serv ice ) ;

$resources = $di−>get ( ’ resources ’ ) ;

Page 30: Zend Framework 2 Components

Considerations for ZF1 usage

27

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

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

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

• Still works good for Service Containers and Data Models

Page 31: Zend Framework 2 Components

Zend\EventManager

Page 32: Zend Framework 2 Components

What is the EventManager?

29

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

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

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

Page 33: Zend Framework 2 Components

But why does that matter?

30

• Allows for handling events without modifying/overwriting frameworkcode.

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

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

Page 34: Zend Framework 2 Components

EventCollection Interface

31

<?phpnamespace Zend\EventManager ;use Zend\ S t d l i b \Cal lbackHandler ;

i n t e r f a c e Even tCo l lec t i on{

p u b l i c f u n c t i o n t r i g g e r ( $event , $context , $argv =ar ray ( ) ) ;

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 , $context ,$argv , $ca l lback ) ;

p u b l i c f u n c t i o n a t tach ( $event , $ca l lback ,$ p r i o r i t y = 1) ;

p u b l i c f u n c t i o n detach ( Cal lbackHandler $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 getHandlers ( $event ) ;p u b l i c f u n c t i o n c learHandlers ( $event ) ;

}

Page 35: Zend Framework 2 Components

Triggering Events

32

<?phpuse Zend\EventManager\EventManager ;

$events = new EventManager ( ) ;$events−>t r i g g e r ( $eventName , $object , $params ) ;/ * Where :

* − $eventName i s the name of the event ; usua l l y thecu r ren t

* method name

* − $ob jec t i s the ob jec t t r i g g e r i n g the event

* − $params are the parameters the handler mightneed to access ,

* usua l l y the method arguments

* /

Page 36: Zend Framework 2 Components

Zend Components as of ZF2

Page 37: Zend Framework 2 Components

Just a quick List

34

• Acl

• Amf

• Application

• Authentication

• Barcode

• Cache

• Captcha

• Code

• CodeGenerator

• Config

• Console

• Controller

• Crypt

• Currency

• Date

• Db

• Debug

• Di

• Dojo

• Dom

• EventManager

• Feed

• File

• Filter

• Form

• GData

• Http

• InfoCard

• Json

• ProgressBar

Page 38: Zend Framework 2 Components

Just a quick list, cont.

35

• Layout

• Ldap

• Loader

• Locale

• Log

• Mail

• Markup

• Meassure

• Memory

• Mime

• Mvc

• Navigation

• OAuth

• OpenId

• Paginator

• Pdf

• Queue

• Reflection

• Registry

• Rest

• Search

• Service

• Session

• Soap

• Stdlib

• Tag

• Test

• Text

• TimeSync

• Tool

• Translator

• Uri

• Validator

• Version

• View

• Wildfire

• XmlRpc

Page 39: Zend Framework 2 Components

There are a bunch of components outthere, choose what you want

Page 40: Zend Framework 2 Components

How To Convert for PHP 5.2

Page 41: Zend Framework 2 Components

Let’s be realistic

38

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

• Closures (Anonymous Functions)

• Late Static Binding

• Garbage Collection

Page 42: Zend Framework 2 Components

Figuring out Dependencies

39

With PHP 5.3’s namespace aliasing, mapping dependencies actuallybecomes really easy; use statements at the beginning of the file willusually tell you what components you need from outside of thatnamespace.

Page 43: Zend Framework 2 Components

Converting Namespaces

40

Some sticking points:

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

• It may be worth renaming the namespace from Zend to ZendX ifusing 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.

Page 44: Zend Framework 2 Components

Conclusions

41

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

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

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

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

Page 45: Zend Framework 2 Components

Questions?

Page 46: Zend Framework 2 Components

Thank You

43

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