2007 zendcon mvc

58
Copyright © 2007, Zend Technologies Inc. Zend Framework MVC Quick Start Matthew Weier O'Phinney PHP Developer Zend Technologies Zend Framework provides rich and flexible MVC components built using the object-oriented features of PHP 5.

Upload: manali-gupta

Post on 10-Nov-2015

226 views

Category:

Documents


1 download

DESCRIPTION

Zend framework overview and basics

TRANSCRIPT

  • Topics OverviewZend Framework OverviewWhat is MVC?Zend_Controller: The 'C' in MVCZend_View: The 'V' in MVCZend_... Where's the 'M'?Putting it TogetherQ & A

  • Zend FrameworkZend Framework Overview

  • What is Zend Framework?Component LibraryLoosely coupled components for general purpose actionsUse-at-will architectureApplication FrameworkCohesive framework for building applications

  • Zend Framework GoalsExtreme Simplicity:Simpler is easier to useSimpler is more stable and less prone to errorSimpler is easier to maintain

  • Zend Framework GoalsShowcase Current Trends:Web ServicesAjaxSearch

  • Zend Framework GoalsStability and DocumentationAll components must have > 80% test coverageAll components must have end-user documentation and use-cases

  • Zend Framework GoalsBusiness FriendlyContributor License Agreement required in order to contribute code, patches, or documentationAll code licensed under the new BSD license

  • Zend FrameworkWhat is MVC?

  • MVC OverviewModel The "stuff" you are using in the application -- data, web services, feeds, etc. View The display returned to the user. Controller Manages the request environment, and determines what happens.

  • MVC InteractionsController View Controller and View can interact Controller Model Controller can pull data from the model for decisioning, or push data to the model View
  • Front ControllerHandles all requestsDelegates requests to 'Action Controllers' for handlingReturns response

  • Zend FrameworkZend_Controller: The 'C' in MVC

  • Zend_Controller: BasicsAction Controllers:Extend Zend_Controller_ActionClass name ends in 'Controller'IndexControllerBlogControllerUnderscores indicate directory separatorsFoo_AdminController => Foo/AdminController.phpNote: rule is different with modulesCamelCasing allowedFooBarControllerSeparate CamelCased words in URLS with '-' or '.':foo-barfoo.bar

  • Zend_Controller: BasicsController Actions:Method the action controller should performPublic methods ending in 'Action'barAction()indexAction()CamelCasing allowedfooBarAction()Separate camelCased words on the URL with '.', '-', or '_':foo-barfoo.barfoo_bar

  • Zend_Controller: BasicsModules:A set of related action controllers, models, and viewsDirectory structure mimics application directory structure:controllers/models/views/Controller class names should be prefixed with module name:Foo_ViewController -> foo/controllers/ViewController.phpModule names may be camelCased as well; follow rules for controllers

  • Zend_Controller: ResponsibilitiesRequest object: contains all information on the request environmentRouter: decomposes environment into various tokens representing the current module, controller, action, etc.Dispatcher: maps the tokens from routing to action controller classes and methods, and executes themResponse object: contains the complete response and has the ability to send it

  • Zend_Controller: Process Diagam

  • Zend_Controller: Dispatch Loop$front->dispatch() handles the incoming requestInstantiates request and response objects if not previously setRoutes requestEnters dispatch loopDispatch ActionInstantiate controllerCall action methodDispatches until request object reports no more actions to dispatchReturns Response (sends by default)

  • Zend_Controller: RoutingDefault Routing:/controller/action/controller/action/key1/value1/key2/value2/module/controller/action/module/controller/action/key1/value1/...

  • Zend_Controller: RoutingModifying Routing: Rewrite Router:Zend_Controller_Router_Rewrite is the default router implementationAllows attaching as many named routes as desiredNamed routes allow pulling routes for later operations, such as URL assembly or determining what in a URL matched.Routes are executed in a LIFO orderRoute interface allows defining your own route types for your applications

  • Zend_Controller: RoutingShipped Route Types:Static: match exactly, and dispatch according to defaultsFastest route; straight equality comparisonStandard: matches by named URL segmentsFlexible and readable, easiest creation of dynamic routes. However, each URL segment is potentially compared against a regexp, making it slow.Regex: matches using PCREFastest and most flexible dynamic route, but potentially the hardest to maintain if not all developers are equally versed in PCRE.

  • Zend_Controller: RoutingCreating a new route:Want to match this: /news/view/12Route: /news/view/:id

  • Zend_Controller: Action ControllersAction ControllersSimply classes that extend Zend_Controller_ActionDefine public action methods for each action you want the controller to handleUse regular public methods when you want to have re-usable or testable functionality

  • Zend_Controller: Action ControllersAction controller triggers and listens to the following events:init(): object instantiationpreDispatch(): prior to dispatching the actionpostDispatch(): after the action has executed

  • Zend_Controller: Action ControllersUtility Methods:_forward($action, $controller = null, $module = null, array $params = null): forward to another action_redirect($url): redirect to another locationrender($action, $name, $noController): render an alternate view script__call($method, $params): use to create 'dynamic' actions or internally forward to a default action

  • Zend_Controller: ViewRendererView integration is automatically available Registered by ViewRenderer action helperCan be disabled$view property of controller contains view objectAssign variables to view: $this->view->model = $model;

  • Zend_Controller: ViewRendererView scripts are rendered automatically during postDispatch() eventView scripts named after controller and action:FooController::barAction() renders foo/bar.phtmlNewsController::listAction() renders news/list.phtmlDisabling the ViewRenderersetNoRender() will disable it for the current actionCalling _forward() or _redirect() never auto-renders

  • Zend_Controller: ViewRendererCustomizing the ViewRenderer:setView()Set view object (allows for custom view implementations!)setViewSuffix()Change the file suffix usedsetView(Base|Script)PathSpec()Set the path specification used for auto-determining the view locationsetResponseSegment()Set the named response segment to render into

  • Zend_ControllerSample Action Controller:

  • Zend_Controller: PluginsWhat are Plugins?Triggered by front controller eventsEvents bookend each major process of the front controllerAllow automating actions that apply globally

  • Zend_Controller: PluginsEvents:routeStartup(): prior to routingrouteShutdown(): after routingdispatchLoopStartup(): prior to fist iteration of dispatch looppreDispatch(): prior to dispatching an actionpostDispatch(): after dispatching an actiondispatchLoopShutdown(): at dispatch loop termination

  • Zend_Controller: PluginsCreating Plugins:Extend Zend_Controller_Plugin_AbstractExtend one or more of the event methodsCreate multi-purpose plugins by extending multiple methodsCreate targetted plugins by extending a single method

  • Zend_Controller: PluginsExample: Two-Step View PluginNote: the above will be superseded shortly by Zend_Layout

  • Zend_Controller: Action HelpersWhat are Action Helpers?Reusable functionalityFunctionality that can be used in multiple controllersFunctionality you want to be able to discretely unit testObjects you wish to persist across controllersUseful for automating processes that involve the action controllersInitialized on-demand, or may be registered with helper brokerFunctionality you may want to swap out later

  • Zend_Controller: Action HelpersCreating Action Helpers:Extend Zend_Controller_Action_Helper_AbstractLast segment of class name is helper nameMy_Helper_Foo -> 'foo' helperMy_Helper_FooBar -> 'fooBar' helperOptionally implement a direct() method for method-like invocationAllows helper to be called as if it were a method of the helper broker

  • Zend_Controller: Action HelpersUsing Action Helpers as Action Controller Event Listeners:init():when the action controller is initializedpreDispatch(): executes after front controller preDispatch() plugins but before action controller preDispatchpostDispatch() executes after action controller postDispatch() but before front controller postDispatch() pluginsNote: helper must be registered with broker for events to trigger

  • Zend FrameworkZend_View: The 'V' in MVC

  • Zend_View: OverviewImplement Zend_View_Interface to create your own template engineDefault implementation (Zend_View) uses PHP as the template languageAssign and retrieve view variables as if they were object members: $view->content = $bodyAccess view variables in view scripts from $this object: Benefits: All of PHP is at your disposalIssues: All of PHP is at your disposal

  • Zend_View: View ScriptsMix HTML and PHPAccess template variables using $this notationKeeps assigned variables in their own scopeEasily distinguish assigned variables from local variablesEasy placeholder implementation: simply assign from view scripts and use in later view scripts

  • Zend_View: View ScriptsUse PHP short tags for shorthand notation:

  • Zend_View: View HelpersClasses that extend the functionality of Zend_ViewUsesAccess models (e.g. add a del.icio.us feed to your page)Format or escape output (e.g. transform wiki text to XHTML)Display logic (e.g., show login buttons if user not logged in)Re-usable display snippets (e.g., search form box)

  • Zend_View: View HelpersUsing View Helpers:Call as if the helper were a method of the view object

  • Zend_View: View HelpersCreating and Using View Helper:Helper name is last segment of class nameMy_View_Helpers_Foo: foo helperMy_View_Helpers_FooBar: fooBar helperRegister helper paths with Zend_View objectOptionally specify a class prefixPaths searched in LIFO orderOverride a helper by registering late

  • Zend_View: View HelpersView Helper Classes:Must have a method named after the helper:

  • Zend_View: View HelpersOptionally allow view awareness by creating a setView() method:

  • Zend_View: FiltersAllow filtering rendered content prior to returning itSimilar to helpers, one class and method per filterUse CasesTransform HTML to PDFTransform HTML to JSONPass X/HTML through tidyInject session IDs

  • Zend FrameworkZend_...: Where's the 'M'?

  • Zend_Model?What is a Model?DatabaseWeb ServicesFeedsConfiguration filesFilesystemImages

  • Zend_Model?How does Zend Framework address the Model?We don't yet, at least not as a generalized component. But we do support it with our specialized components:Zend_Db_TableZend_ServiceZend_Feedetc.

  • Zend FrameworkPutting it Together

  • Putting it TogetherFilesystem Layout:

  • Putting it TogetherThe Bootstrap file (index.php): Simplest:

  • Putting it TogetherBootstrap File (index.php): More Advanced:

  • Putting it TogetherHello World! IndexController:

  • Putting it TogetherHello World! ErrorController:

  • Putting it TogetherHello World! View scripts:

    Copyright 2007, Zend Technologies Inc.

    Thank you!More on Zend Framework:http://framework.zend.com