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.

36af1ab1897f88d3d56d91ed1aece5d5?s=128

Adam Lundrigan

November 02, 2012
Tweet

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. What is so different about ZF2?

  4. • 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
  5. • 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
  6. Class Naming ZF1 had some looooong class names: ZF2 brings

    relief through namespaces!
  7. 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
  8. 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
  9. 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
  10. 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)
  11. 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
  12. 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
  13. • 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
  14. • 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
  15. • 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
  16. • 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
  17. • 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
  18. • 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
  19. • 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
  20. 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
  21. 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.
  22. Application Structure Source: Zend Framework 2 Quickstart, Enrico Zimuel http://www.slideshare.net/e.zimuel/zend-framework-2-quick-start

  23. Application Configuration config/application.config.php

  24. 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...
  25. Module Structure Source: Zend Framework 2 Quickstart, Enrico Zimuel http://www.slideshare.net/e.zimuel/quick-start-on-zend-framework-2

  26. 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*
  27. 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
  28. Migrating from ZF1 to ZF2

  29. 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
  30. Bootstrapping in ZF2 • Fast lazy-loading of resources via service

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

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

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

    for class ( == slow) • Can also act as a front controller plugin (init / preDispatch / postDispatch)
  34. Controller Action Helpers in ZF2 • Now called "controller plugins"

  35. View Helpers in ZF1 • Searches configured library paths for

    class ( == slow) • HelperBroker automatically calls method named same as class name suffix
  36. 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
  37. View Helpers in ZF2

  38. 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
  39. View Helper BC breaks • json view helper signuature has

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

    • I18n • InputFilter • Math Newly-added • ModuleManager • Mvc • Serializer • ServiceManager • Stdlib
  41. 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
  42. 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
  43. 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)
  44. THANK YOU! Please rate this talk on joind.in: http://joind.in/7401

  45. 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