Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Paradigm Shift: An Introduction to ZF2 for ZF1 Developers

Paradigm Shift: An Introduction to ZF2 for ZF1 Developers

This session will delve into the details Zend Framework 1 developers need to know about the shiny new 2.0 release. Starting from a high-level overview of the evolution of ZF2 and it's major differences from ZF1, we will dive into common usage scenarios for ZF1 and it's major components and detail how to accomplish these "the ZF2 way". Along the way we will also explore ways to leverage ZF2 in your exisitng ZF1 applications, plus highlight migration paths that will help you migrate your applications from ZF1 to ZF2 as painlessly as possible.

Adam Lundrigan

November 02, 2012
Tweet

Other Decks in Programming

Transcript

  1. Paradigm Shift An Introduction to ZF2 for ZF1 Developers Adam

    Lundrigan adam.lundrigan.ca @adamlundrigan
  2. Who am I? • Just this PHP guy, you know?

    • B.Sc CompSci, Zend Certified Engineer • Minor Zend Framework contributor • Co-founder of NLWebDevs • 13 years of LAMP, 7 years professionally
  3. • SVN+JIRA Git+GitHub • No more CLA! • Docs &

    "non-core" components spun off • Big effort around improving design • Adopt 5.3, prepare for 5.4 • Finally properly componentized Project Organization & Structure
  4. • Hard-coded deps • Singleton • Registry • DI-unfriendly •

    Magic by default Rethinking Core Principles Zend Framework 1 • Decouple & Simplify • DI, Events to the max! • Magic is optional • Interoperability • Emphasis on performance Zend Framework 2
  5. Class Autoloading • Zend\Loader\ClassMapAutoloader ◦ 25-85% faster than path-based autoloader

    • Now available in ZF1 (1.12) as Zend_Loader_ClassMapAutoloader • Use EdpSuperluminal! https://github.com/EvanDotPro/EdpSuperluminal ◦ Compiles cache of all ZF2 classes used by your application ◦ Subsequent requests get all necessary classes with just one include ◦ Needs to be extended to cache arbitrary namespaces
  6. Events, Events, Events • Robust, lightweight Event Manager component •

    Signals/Slots pattern • Supports scoping, listener aggregation, short- circuiting, wildcards, listener priorities • MVC is completely event-driven • Now part of 1.12: Zend_EventManager
  7. Service Location & DIC • Two Components: ◦ Zend\Di: meta-programming

    of dependency wiring ◦ Zend\ServiceManager: factory-based DIC • ServiceManager also provides a standard interface defining a minimal service locator • Everything-as-a-Service™ • Heavy use in MVC & plugin managers
  8. Service Location & DIC Service Manager supports many definition "modes"

    • Explicit (name aliases an object instance) • Invokables (name aliases a class name) • Factories (name aliases a callable which produces an object instance) • Aliases (name aliases another name) • Abstract Factories (fallback for unregistered names)
  9. Forms, Filtering, Validation • Clean separation of concerns • Baked-in

    object binding, hydration and collections • Assistance for client-side collection manipulation • Filtering and Validation plugins largely unchanged • Zend_Validate is now Zend\Validation • Form filtering handled by Zend\InputFilter
  10. Database Abstraction • Internal decoupling via subcomponents: Adapter, Sql, Platform,

    Metadata, ResultSet • Table & Row Data Gateway patterns • Decoupled model layer via new ResultSet subcmp. ◦ ZF1: models extended Zend_Db_Table_Row ◦ ZF2: hydration of POPOs • Greatly improved SQL abstraction layer ◦ Now supports nested conditions! \o/ ◦ Improved support for predicates and functions
  11. • Whole new component: Zend\Escaper • Context-specific, encoding-aware escaping •

    View helpers for ease of use ◦ escapeHtml HTML body ◦ escapeHtmlAttr HTML attributes ◦ escapeJs Javascript content ◦ escapeUrl URI and Parameters ◦ escapeCss CSS content Output Escaping & XSS
  12. • Completely redesigned from the ground up • Zend_Application +

    Zend_Controller = Zend\Mvc • Cleaner separation of concerns • IoC, Event patterns used everywhere. Flexibility++ • Not just for HTTP! MVC: Overview Migration pain will emanate from here
  13. • Zend_Controller Zend\Mvc\Controller • No more front controller or dispatcher

    • ZF1's "controller plugin" pattern dropped (replaced by events) • Terminology change: "action helpers" now called "controller plugins" • REST controller is now first-class controller type MVC: Controllers
  14. • Big improvement over ZF1 routing • No more "router",

    just RouteStack strategies • Centerpiece is TreeRouteStack • Routing trees composed of distinct route types ◦ Literal ◦ Regex ◦ Wildcard ◦ Segment • RouteMatch object encapsulates match results MVC: Routing ◦ Hostname ◦ Scheme ◦ Method ◦ Query
  15. • Same name, totally new component. • Zend_Layout axed, replaced

    by ViewModel system • Comprised of three sub-components ◦ Strategy: determines which renderer to use ◦ Resolver: resolves template alias to filename ◦ Renderer: renders ViewModel into output • Zend\Mvc\View puts the V in MVC MVC: View
  16. • Flexible, extensible template alias resolver • Bundled strategies ◦

    PathStack: define view directories ◦ Map: define direct alias-to-file mappings • Single module can mix & match strategies via AggregateResolver meta-strategy MVC: Zend\View\Resolver
  17. • Flexible, extensible template renderer • Renderers for common output

    types are bundled ◦ PhpRenderer ◦ JsonRenderer • Easily implement new renderers (ie: Twig) • Bundled renderers support nested ViewModel rendering (TreeRendererInterface) MVC: Zend\View\Renderer ◦ FeedRenderer ◦ ConsoleRenderer
  18. MVC: ZFTool • Replacement for Zend_Tool • Distributed as add-on

    module https://github.com/zendframework/ZFTool • Provides controllers for common maintenance tasks ◦ List modules in application ◦ Classmap generator ◦ ZF version introspection • It's a work in progress
  19. Application Structure • ZendSkeletonApplication is the gold standard https://github.com/zendframework/ZendSkeletonApplication •

    Provides a functional example ZF2 application demonstrating how to use the MVC • Just a recommendation. You can build a ZF2 application in (nearly) any form you can dream up ...but (please!) follow the standard unless you have a legitimate need to deviate.
  20. Modules! • ZF1 modules weren't really modules, just autoloader namespaces

    tied to URI segment • ZF2 gives us truly reusable modules! • Minimal requirement: just a Module class! Of course, this doesn't provide much functionality...
  21. Modules! • Common functionality is out there already ◦ ZfcUser

    ◦ ZfcAdmin ◦ AssetManager ◦ DoctrineORMModule • Community-led ZF-Commons initiative formed to provide common functionality through modules ◦ BjyAuthorize ◦ ScnSocialAuth ◦ SpeckCommerce* ◦ Ensemble*
  22. Application & Module Configuration • Config files/methods can return a

    PHP array or Traversable object (ie: Zend\Config) • Configuration Merging 1. Module configurations (Module::getConfig) are merged together in specified load order 2. Application configurations (glob/static paths) are merged into result of #1 3. Service configurations (Module::get*Config) are merged together, then merged into result of #2 • Output of #1 & #2 can be cached, #3 cannot
  23. Bootstrapping in ZF1 • Slow, inefficient, dumb • Every resource

    was bootstrapped in every request, even if it wasn't explicitly needed • No built-in way to lazy-load resources
  24. Bootstrapping in ZF2 • Fast lazy-loading of resources via service

    locator • Define a SL factory to create the resource on-demand
  25. Controller Plugins in ZF1 • Searches configured library paths for

    class ( == slow) • preDispatch & postDispatch could be implemented directly in controller class
  26. Controller Plugins in ZF2 • Replaced by triggered events (bootstrap,

    route, dispatch, render, finish) • Pre/Post determined by priority (> 0 = pre, < 0 = post)
  27. Controller Action Helpers in ZF1 • Searches configured library paths

    for class ( == slow) • Can also act as a front controller plugin (init / preDispatch / postDispatch)
  28. View Helpers in ZF1 • Searches configured library paths for

    class ( == slow) • HelperBroker automatically calls method named same as class name suffix
  29. View Helpers in ZF2 • Multiple components expose view helpers

    (View, I18n, Form, Navigation) • New view helpers for: ◦ HTML5 form elements, CAPTCHA rendering ◦ I18N translation & formatting ◦ Context-specific escaping ◦ View model manipulation
  30. View Helper BC breaks • Action, UserAgent, TinySrc removed •

    URL view helper has reversed argument order • baseUrl is now basePath • escape replaced by context-specific helpers • layout is significantly different
  31. View Helper BC breaks • json view helper signuature has

    changed • Currency is now CurrencyFormat (I18n)
  32. Summary of Component Changes • Di • Escaper • EventManager

    • I18n • InputFilter • Math Newly-added • ModuleManager • Mvc • Serializer • ServiceManager • Stdlib
  33. Summary of Component Changes • Acl • Application • Auth

    • CodeGenerator • Controller • Reflection • Translate Zend Framework 1 • Permissions\Acl • Mvc • Authentication • Code\Generator • Mvc\Controller • Code\Reflection • I18n Zend Framework 2 Renamed Components
  34. Summary of Component Changes • Currency • Date • Layout

    • Locale • Measure • Test • Tool Discontinued • Queue • Pdf • Service • GData • Rest • OpenID • Oauth • Cloud • Amf Split from main repo • TimeSync • Search • Markup
  35. From the Trenches: Our Process 1. Refactor ZF1 app: thin

    controllers, fat service layer 2. Make service layer DI-friendly 3. Divide service layer into functional areas 4. Define Service Manager factories for service layer 5. Replace common functionality with 3rd-party modules 6. Build out ZF2 versions of ZF1-dependent services (eg: database mappers, plugins, helpers)
  36. Other Recent ZF2 Presentations • Zend webinars ◦ http://www.zend.com/en/resources/webinars/framework •

    Modules ◦ http://blog.evan.pro/introduction-to-modules-in-zend- framework-2-talk-at-zendcon-2012 ◦ http://mwop.net/blog/2012-09-19-zf2-module-screencast.html • Router ◦ http://stuff.dasprids.de/slides/zendcon2012/introducing-the- new-zend-framework-2-router/presentation.html • ZendCon 2012: http://joind.in/event/view/951 http://joind.in/event/view/1106