SlideShare a Scribd company logo
Zend Framework WorkshopBy Kevin SchroederTechnology EvangelistZend Technologies
About meKevin SchroederTechnology Evangelist for ZendProgrammerSys AdminAuthorIBM i Programmer’s Guide to PHPYou want to do WHAT with PHP? Race Ferraris on the weekendMy Honda has a dismal win record
Follow us!Zend Technologieshttp://twitter.com/zendhttp://twitter.com/kpschrade (me!)www.eschrade.com
A quick note on Zendcon… BE THERE!!Learn PHP best practices
Discover new advances
Gain new insights
Deploy and scale large PHP applications
Explore new technologies like NoSQL and Cloud Computing
Learn how to effectively leverage Zend Framework and Zend Framework 2.0What does Zend doZend FrameworkZend Studio (8.0 in public beta 1)Zend ServerMonitoring,Code tracing (freaking cool!!)Job queuingHA Session ClusteringZend Server Cluster ManagerLots and lots of trainingPHP, Zend Framework certifications
AgendaThe BasicsIntroductionCoding StandardsInstalling Zend FrameworkAutoloadingZend_SessionZend_ConfigZend_MailZend_ValidateZend_FilterZend_TranslateZend_FormMVCA little more advanced
Zend_Application
Zend_Db
Table/Row Data Gateway
Services
Theory
Zend_Json_Server
Zend_Amf
Zend_Service_TwitterWhy do we use PHP?
Sample PHP Script<html><head></head><body><?phpfunction questionp($input) {    return strrpos ( $input, '?' ) === strlen ( $input ) - 1;}?><?phpif (! isset( $_POST ['submit'] )) {// if the "submit" variable does not exist the form has not been submitted, so display form?><form action="<?phpecho $_SERVER['PHP_SELF']; ?>"method="post">Enter your question: <input name="question" size="50"><input type="submit" name="submit" value="Ask"></form><?php} else {// if the "submit" variable exists the form has been submitted, so look for and process form data,// displaying the resultif(questionp($_POST['question'])) {if(rand(0, 1)): echo 'yes'; else: echo 'no'; endif;} else {echo 'Don\'t you know what a question is?';    }}?PHP: Past and Present| 8
Anatomy of a PHP ApplicationPHP: Past and PresentPresentationApplication ControlDatabase AccessBusiness LogicPresentationApplication ControlBusiness LogicPresentation| 9
Anatomy of a PHP ApplicationPHP: Past and Presentindex.php3index.php3index.php3index.php| 10
Anatomy of a PHP ApplicationPHP: Past and Presentindex.php3index.php3index.php3index.phpindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php| 11
Anatomy of a PHP ApplicationPHP: Past and Presentindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.phpindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.phpindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.phpindex.php3index.php3index.php3index.php3index.php3index.php3index.php| 12
Anatomy of a PHP ApplicationPHP: Past and Presentindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3| 13|
Anatomy of a Modern PHP Application |   22-Sep-10PHP: Past and PresentPresentationSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlApplication ControlSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpBusiness LogicSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpDatabase AccessSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.php| 14
Zend FrameworkMake everything as simple as possible, but no simpler.	- Albert Einstein
PHP ProblemsHow can we promote reuse and standards in a strong culture of decentralization?How can we propagate best practices across a community of cowboy coders numbering in the millions?How do we manage the newfound complexity of large PHP applications?How do we promote integration with commercial technologies in a community that has been developed in parallel to these technologies?How do we write better PHP applications? |   22-Sep-10Name of this section| 16
The Answer?Name of this section| 17
What is Zend Framework?An open source, MVC-based, full-featured PHP frameworkA set of use-at-will components; a component libraryA vehicle through which Zend disseminates best practicesA communityA philosophyA standardA gateway to the larger PHP community |   22-Sep-10PHP: Past and Present| 18
What sets ZF apart?High quality code; all components have unit test coverage of > 80% (both lines and branches) and the tests are run against the framework continuouslyA use-at-will architecture that allows developers to mix and match their favorite technologiesA contribution process that both guarantees quality and encourages active community contributions while protecting against intellectual property claimsWe only tackle problems when we can bring value that isn’t currently available in the PHP communityWe believe that web services must be first-class citizens for today’s Web 2.0 applications |   22-Sep-10PHP: Past and Present| 19
Our Technology Partners… and more
Supported by All Popular PHP IDEs
Over 50 Books Written
74% of all Zend Framework Applications are Business-Critical* Zend Framework Developer Survey, Dec. 2009
Dojo Integration+In May, 2008 Zend announced a collaboration between the Zend Framework and Dojo Toolkit projects. Zend Framework 1.6 contains the first integration points between these 2 projects:JSON-RPC Serverdojo.data EnvelopesDojo View HelperDijit integration with Zend_Form & Zend_ViewDojo Library Re-distribution
Autumn, 2008Download & InstallZend FrameworkDownload the latest version of Zend Framework and extract the contents of the library folder to your project's library directoryhttp://framework.zend.com/downloadYou should now find the top-level Zend directory which contains all Zend Framework components under your library directoryThat's it! Zend Framework is now installed and ready to use
Autumn, 2008What’s in Zend Framework?Simple, convenient object-oriented solutions to common web application development tasks:MVC web app framework(model-view-controller)Database accessLucene-compatible Search engineInput filtering and validationAuthenticationAccess controlSession handlingI18N, locales, translationPDF file reading and writingHTTP clientForm HandlingXML-RPCREST web servicesRSS and Atom feedsLoggingMail reading and sendingCachingConfiguration filesCommand-line option parsingMUCH, MUCH more!
Autumn, 2008Zend Framework Overview
Where to start
Don’t start with MVC firstThere are MANY libraries that you can utilize firstA trustworthy saying“Don’t use a framework until you know why you need a framework”Don’t use MVC until you know you need MVCOr have at least experienced the pain of managing a large application without it
Things to knowAll ZF-based classes start with Zend_If you build a library that utilizes ZF, do not prefix your classes with that (breaks coding standards)Use the autoloaderUse plugin loadersStart small
Coding StandardsFiles with ONLY PHP code start with <?php and have no closing tagIndentation uses 4 spaces, tabs not allowedLines end with Unix EOLClass naming standards changed after 1.9 to prepare for PHP 5.3 and ZF 2Function/method declarations Anything marked private/protected is prefaced with an underscore (private $_var = null)Numbers are permitted in variable/method/function names, but are not recommended
Coding StandardsGlobally defined variables/functions are allowed, but not recommended (use registry/static methods instead)Variables/methods/functions are named using camelCaseThere is some debate one what a camel looks like when using an acronym (e.g. PDF)Global constants are allowed, but discouraged.  Use class constants insteadClass constants should be UPPER_CASE_WITH_UNDERSCORE“Variable substitution is {$allowed} but not ${allowed}”‘If no variable substitution is needed then use single quotes’For arrays, negative index keys are not allowed
Coding StandardsOne class per fileBracesFinal brace is always on its own lineMethod/function calls start on the next lineConditional statements/loops start on the same lineBreak clauses MUST have a defaultAll functions/methods/class members MUST have a PHPDoc blockRead the coding standards at http://framework.zend.com/ in the docs
How to start?Start simple, use utility classesZend_LoaderZend_DateZend_ConfigZend_SessionZend_TranslateZend_ValidateZend_FilterZend_Form (!)Others
Utility Classes
Zend_LoaderUsed to include files for classes that have not been loaded yetIt searches the include_path for the requested class Two types of loadersAutoloaderJust a standard autoloaderPluginLoaderUsed for loading classes based off of a prefix
Zend_Loader_AutoloaderInitializeZend_Loader_Autoloader::getInstance();Register pseudo namespaceZend_Loader_Autoloader::getInstance()   ->registerNamespace('Myapp_');Set the autoloader for all namespacesZend_Loader_Autoloader::getInstance()   ->setFallbackAutoloader(true);
Zend_Loader_PluginloaderUsed to load named classes, not autoloadUsed extensively by several ZF components
Zend_Loader_Pluginloader/library/MyApp/MyComponent/Classone.php/library/MyApp/AnotherComponent/Classtwo.php$loader = new Zend_Loader_PluginLoader();$loader->addPrefixPath(    'MyApp_MyComponent',    'MyApp/MyComponent');$loader->addPrefixPath(    'MyApp_AnotherComponent',    'MyApp/AnotherComponent');
Zend_Loader_Pluginloader$loader->load('Classone');$loader->load('Classtwo');
Zend_SessionUse this instead of $_SESSION.  Why?Works much better for complex applicationsAllows for easier separation of components$ns = new Zend_Session_Namespace('Component-1');$ns = new Zend_Session_Namespace('Component-2');
Zend_SessionGood API (standard session ext has very minimal API)public function lock();public function unlock();public function apply($callback);public function applySet($callback);public functionsetExpirationSeconds(    $seconds,    $variables = null);public function setExpirationHops(    $hops,    $variables = null,    $hopCountOnUsageOnly = false);
Zend_ConfigProvides a way of dealing with configurationA consistent API for getting and setting valuesImplements Countable, Iterator (uses SPL)Existing mechanismsPHP Arrays (great with opcode caches)INI FilesXML FilesYour own (Don’t use the DB)
Zend_ConfigGenerally used forDatabase adapter credentialsCaching optionsPathsZend_Application uses a LOT of configuration
Using Zend ConfigYou can retrieve data by section
Using Zend_ConfigYou can have inheritance between sectionsBest practice: inherit from [production]
Zend_ValidateUsed to provide integratable validation toolingDon’t build it yourself!!Some example validatorsEmail AddressCredit CardString LengthHost nameAnd about 80 othersChainable using new Zend_Validate()
Zend_Validate – Building your ownMust implement Zend_Validate_InterfaceZend_Validate_Abstract is a better choice to extendConstructor is optional, used for passing options
Zend_FilterUsed to filter dataSome examplesHtmlEntitiesEncrypt/DecryptStripTagsStripNewLines
Zend_FormNew to ZF 1.5 (one of the best features)HandlesRendering the formEscaping your outputFiltering your inputValidating your data
Zend_Form – Simple usage$form = new Zend_Form();$form->setMethod('POST');$form->setAction('/submitform.php');$form->setView(new Zend_View());$form->addElement('text', 'email');$form->addElement('text', 'name');$form->addElement('submit', 'submit');echo $form;
Zend_Form – Less simple usageForms and form elements have a LOT of options$form->addElement(    'text',    'email',    array(        'label'    => 'Email',        'required' => true    ));
Zend_Form – Adding validators$form->addElement(    'text',    'email',    array(        'label'=> 'Email',        'required'=> true,        'validators'=> array(            'EmailAddress'        )    ));Don’t use validator objects; name them insteadBut make sure to test that they work
Zend_Form – Adding filters$form->addElement(    'text',    'name',    array(        'label'=> 'Name',        'required'=> true,        'filters'=> array(            'Alpha'        )    ));
Zend_Form - trickAll of the configuration parameters are passed to getters and settersWant to know what configuration options are available?  Look at the setterssetLabel() = array(‘label’ => ‘name’)setValidators()setName()setOrder()setRequired()
Zend_Form – Architecting your appBest practicesSubclass Zend_FormVery reusableVery testableCreate forms to match your existing data structureHave pre-defined forms that match up to existing modelsLet the designers worry about layoutZend_Form allows for CSS heavy design (ok, that’s good and bad )
Zend_Form – Architecting your appIf using with MVCPlace in /application/formsPreface with Form_Use a plugin loaderIf notPlace it in a standard library path and use the autoloader
Zend_LogConceptsLogger – usually an instance of Zend_LogWriter – the mechanism which writes the log entry to the storage mediumMust extend Zend_Log_Writer_AbstractFilter – used to determine IF a log entry should be sent to the writerMust implement Zend_Log_Filter_InterfaceFormatter – creates the text string that will be sent to the writer
Zend_LogSeveral logging levels (BSD syslog)EMERG - Emergency: system is unusableALERT - Alert: action must be taken immediatelyCRIT - Critical: critical conditionsERR - Error: error conditionsWARN - Warning: warning conditionsNOTICE - Notice: normal but significant conditionINFO - Informational: informational messagesDEBUG - Debug: debug messages
Zend_LogAvailable writersDbFirebugMailMockCan write to multiple writers at a timeEach writer can have multiple filtersNull
Stream
Syslog
ZendMonitorMVC
MVCModelAn object that represents a unit of data/functionalityViewThe user interfaceControllerWhere your business logic lies
MVCIt’s best to not use “pure” MVCUse the “thin controller” architecturePlace as much of your business logic in the model as possibleReduces code duplicationEnhances code testability
Zend_ControllerComponent where the Controller portion of MVC residesSeveral conceptsFront ControllerAction ControllerPluginsHelpers
Zend_Controller – Start to finishFront controllerRouterDispatcherAction controller
MVC Request Lifecycledispatch() – Starts the dispatch processrouteStartup() – Called prior to parsing the URL for the requestrouteShutdown() – Called immediately after the module, controller and action have been determineddispatchLoopStartup() – Called immediately before the dispatch loop startspreDispatch() – Called at the beginning of each dispatch loop
MVC Request Lifecycleinit() – Called from inside the controller’s constructorpreDispatch() – Called for each action helper that is currently initializedpreDispatch() – A hook on the current controller object *Action() – The individual action that was requested during the routing processpostDispatch() – A hook in the current controller object
MVC Request LifecyclepostDispatch() – Called for each loaded action helperpostDispatch() – Called for each plugindispatchLoopShutdown() – The last hook to be executed
Front ControllerThe “access point” for the application
Action ControllersExtends Zend_Controller_ActionAccess $_GET, $_POST via request objectPass output/headers to response object
Accessing an action controller
Controller PluginsAllows you to execute functionality at some point along the execution chainPlugins are typically not interactive like helpersNeed to extend Zend_Controller_Plugin_Abstract
Controller Plugins – Hooks
ControllerPlugin - Exampleclass Esc_Application_Plugin_Maintenance	extends Zend_Controller_Plugin_Abstract{    public function routeShutdown(Zend_Controller_Request_Abstract $request)    {        $request->setActionName('index');        $request->setModuleName('default');        $request->setControllerName('maintenance');    } }
Controller HelpersInject on-demand functionality into action controllersCacheContext Switching (“Do I use HTML, JSON, XML?”)View RendererBuild your ownMinimize the need to extend Zend_Controller_ActionHas init(), preDispatch(), postDispatch() hooksOnly called if a helper object has been instantiated
Controller Helpers – Building your ownMust extend Zend_Controller_Action_Helper_AbstractMust be registered with the helper brokerZend_Controller_Action_HelperBroker::addPath(	APPLICATION_PATH.'/helpers',	'Helper');Call from the controller$this->_helper->Sendemail(	'Kevin Schroeder',	'kevin@zend.com',	'We did something in the last request');
Zend_ViewUsed to handle the view (user interface) from BLOlder style apps have the two mixedCan be used separately from MVC (if you like)Useful if you want to re-use view helpers or form componentsIf using MVC, generally stored in controllers/../views/script
Zend_View – Step 1: Assigning data$data = array(    array(        'author' => 'Kevin Schroeder',        'title' => 'The IBM i Programmer\'s Guide to PHP'       ),    array(        'author' => 'Kevin Schroeder',        'title' => 'You want to do WHAT with PHP?'       ));Zend_Loader::loadClass('Zend_View');$view = new Zend_View();$view->books = $data;echo $view->render('booklist.php');
Zend_View – Step 2: Rendering data<?php if ($this->books): ?>      <table>      <tr>        <th>Author</th>            <th>Title</th>        </tr>        <?phpforeach ($this->books as $key => $val): ?>        <tr>        <td><?php echo $this->escape($val['author']) ?></td>            <td><?php echo $this->escape($val['title']) ?></td>        </tr>        <?phpendforeach; ?>  </table><?php else: ?><p>There are no books to display.</p><?phpendif;?>
Using the ViewRendererAn action helper that is loaded by defaultExecutes in the postDispatch() hookExamines the controller/action combination and automatically runs the proper view scriptIndexController::indexAction()/views/scripts/index/index.phtml
View HelpersView helpers make your life easierUsed to provide additional functionality similar to an action helper, but for the viewReferenced via the $this object when in a viewLoaded using a plugin loaderUsed to keep logic out of the view (very important)Try to limit views to if and foreach statements
View Helpers ExamplesEasy translation integrationecho $this->translate('Hello World');Capturing JS so it can be output elsewhere<?php $this->headScript()->captureStart(); ?>alert('Hello World');<?php $this->headScript()->captureEnd(); ?>
View HelpersYou can build your own!Does not need to implement any interface or abstract classGenerally placed in /views/helpers (configurable)Must have a method name defined as the same name of the classMy_Helper_Sendemail must have a method called sendemail().class My_Helper_Sendemail{	public function sendemail($to, $subject, $message)	{		// Haven't gotten to Zend_Mail yet :-)		mail($to, $subject, $message);	}}
Using PartialsPartials are used to render small, re-usable portions of the viewHandled via a view helperPartialPartialLoopVery useful for any iterative functionalityArraysZend_Db_Table_RowsetAnything implementing the Iterator interface
The ModelUnlike other frameworks it is any class that represents your data or business logicCould be a service objectCould be a text fileCould be an LDAP entryCould be a Zend_Db object
Zend_DbDatabase abstraction layer (as opposed to access abstraction layer)Several different database vendors are supportedAbstractions for common functionality such as select, insert, update, delete, limit, offset or transactionsConnects to the database on demandAdapter instance is usually created via Zend_Db::factory()Integrated database profiling
Zend_Db_SelectProvides a vendor-independent mechanism for creating select statementsVery useful, but be careful of the unintended consequences of abstraction$select->from('table')   ->where('table_id = ?', $_GET[‘val']);Output: SELECT `table`.* FROM `table` WHERE (table_id = ?)Supports multiple join types, where, group by, order, etc.
ORMUses the Table/Row Data Gateway Design PatternsOne class to represent the tableOne class to represent a row in the table
ORM – The TableTable classes extend Zend_Db_Table_AbstractHandles references to other tables class Model_DbTable_Comment extends Zend_Db_Table_Abstract{    protected $_name = 'comment';    protected $_rowClass = 'Model_Comment';    protected $_referenceMap    = array(        'Content' => array(            'columns'           => 'content_key',            'refTableClass'     => 'Model_DbTable_Content',            'refColumns'        => 'content_key'        ),    );}
ORM – The RowModel classes extend Zend_Db_Table_Row_Abstractclass Model_City extends Zend_Db_Table_Row_Abstract{}Row data is accessed via a __get callGood idea to use getters and setters to access them(great for code completion)
Fetching Data$dbTable = new Model_DbTable_Comment();$comment = $dbTable->find($_GET['id']);$dbTable = new Model_DbTable_Comment();$select = $dbTable->select()  ->where('active = ?', $_GET['active']);$comment = $dbTable->fetchRow()->current();
ORM - RelationshipsRetrieve an instance of the row classCall a wacked method call which calls __call() and figures out which db table object to load and query on.class Model_DbTable_Comment extends Zend_Db_Table_Abstract{    protected $_name = 'comment';    protected $_rowClass = 'Model_Comment';    protected $_referenceMap    = array(        'Content' => array(            'columns'           => 'content_key',            'refTableClass'     => 'Model_DbTable_Content',            'refColumns'        => 'content_key'        ),    );}
Calling a related object$tabs = $comment      ->findModel_DbTable_TagViaModel_DbTable_TagContent();Write a getter that defines that in your modelclass Model_Content extends Esc_ModelAbstract{    public function getTags()    {        return $this            ->findModel_DbTable_TagViaModel_DbTable_TagContent()    }}
Unit Testing MVC
Unit TestingWhy Unit Test?Simplify maintenanceIt defines expectations It describes behaviors identified by the application It tells us when new changes break existing code and behaviors
TermsUnitThe piece of code you are testingTestA piece of code that calls the piece of code you’re testingAssertionValidating return types or results of the testCode CoverageA report on which lines of code have been testedUsed to determine additional tests that need to be writtenContinuous IntegrationThe continuous application of quality control, i.e. unit tests
Testing the modelThe easiest of allTest classes typically extend PHPUnit_Framework_TestCase
Testing the controllerSetting up the testTest class extends Zend_Test_PHPUnit_ControllerTestCaseIf testing Zend_Application make sure you add the bootstrap in the setUp() methodMake sure you reset() your testsResponseRequestLayoutHelper Broker
Testing the controllerYou can testRouting (also good for checking authorization)Response codesOutput (we’ll look at that next)
Testing the viewBest tested through the controllerDefine which HTML elements need to be present on the page and verify that they exist or have certain valuesCan be done usingCSS SelectorsXpath Queries
Zend_LayoutImplements Two Step View patternSame name as a dance in Texas, but that’s not important
A little more advanced…
Zend_ApplicationUsed for defining an application contextZend_Controller_Front just handled the brokering of the requestZend_Application handles Bootstrapping (dev/testing/staging/production)Creating the autoloaderDispatchingResource creation
BootstrappingImplements Zend_Application_Bootstrap_BootstrapperUsed to bootstrap (set up the environment) and then execute the requestMost applications can simply extend Zend_Application_Bootstrap_BootstrapThis is what we will assume you are using
BootstrappingResource methodsUse the resource autoloader Zend_Application_Module_Autoloader placed in _initAutoload()OrderZend_Application::bootstrap()Bootstrap class instantiatedAny methods starting with _init() are called and the return value is placed in a containerAction retrieves the resource through calling getInvokeArg() and naming the resource
BootstrappingBootstrap class is instantiated every time so DON’T put everything there (horrible for performance, PHP loves lazy loading)One option is to override hasResource() method in Bootstrap so that it instantiates a resource only when it is neededBest practice?  Don’t know.  Kevin’s practice?  Yes.  Therefore it is good
ResourcesPluggable pieces of functionality tied to the applicationTies functionality directly in with the configurationSample of existing pluginsCachemanagerDbLogFrontcontrollerTranslate
Services
Service TheoryMany services have a very similar execution flowReceive requestFind class that can service the requestInstantiate object that can handle the requestReturn result to clientWhy re-invent the wheel?
Zend_ServerBase component for several service-oriented componentsPrimarily used for reflection and a standard interfaceActual implementation is left to component
Zend_*_ServerSeveral components implement Zend_Server_AbstractUseful for standardized web service implementationforeach (glob(APPLICATION_PATH.'/mappers/*.php') as $dir) {$name = substr(basename($dir), 0, -4);    $class = 'Mapper_' . $name;    $serviceHandler->setClass($class, $name);}echo $serviceHandler->handle();Using data mappers are your key to happiness$serviceHandler = new Zend_Json_Server();$serviceHandler = new Zend_Amf_Server();$serviceHandler = new Zend_Xml_Server();
Writing Re-usable ModelsWrite your application logic once, but use it in many different waysWhy? MVC is only one consumerCan be called by job scripts, message systems, queues, etc.Service endpoints can act as consumers(Hint: JSON-RPC is a good way to feed your Ajax applications)112
What?Domain Models
The individual resources and units of work in your application
E.g. user, team, backlog, sprint, etc.
E.g., object relations, transactions, queries
Service Layers
Public API of the application; i.e., the behaviors you wish to expose
Logic for injecting dependenciesService Layer in Perspective
Benefits to Service LayersAllows easy consumption of the application via your MVC layer

More Related Content

PDF
Beginning PHP
Mohammed Safwat
 
PPT
Coldfusion
Ram
 
PPTX
Learn PHP Lacture1
ADARSH BHATT
 
PPTX
Writing High Quality Code in C#
Svetlin Nakov
 
PDF
109842496 jni
Vishal Singh
 
PDF
Web programming UNIT II by Bhavsingh Maloth
Bhavsingh Maloth
 
PPTX
API Documentation Workshop tcworld India 2015
Tom Johnson
 
PPTX
API workshop: Deep dive into Java
Tom Johnson
 
Beginning PHP
Mohammed Safwat
 
Coldfusion
Ram
 
Learn PHP Lacture1
ADARSH BHATT
 
Writing High Quality Code in C#
Svetlin Nakov
 
109842496 jni
Vishal Singh
 
Web programming UNIT II by Bhavsingh Maloth
Bhavsingh Maloth
 
API Documentation Workshop tcworld India 2015
Tom Johnson
 
API workshop: Deep dive into Java
Tom Johnson
 

What's hot (17)

PPTX
API Documentation -- Presentation to East Bay STC Chapter
Tom Johnson
 
PDF
PHP Interview Questions and Answers | Edureka
Edureka!
 
PPTX
T4 presentation
Gary Pedretti
 
DOCX
Guidelines php 8 gig
Ditinus Technology Pvt LTD
 
PPTX
Listen and look at your PHP code
Gabriele Santini
 
PDF
Object oriented-programming-in-c-sharp
Abefo
 
PDF
Hack in the Box GSEC 2016 - Reverse Engineering Swift Applications
eightbit
 
PPT
Introduction to c_sharp
HEM Sothon
 
PPTX
Net serialization
Greg Sohl
 
PDF
Php Interview Questions
UmeshSingh159
 
PPT
Using Zend_Tool to Establish Your Project's Skeleton
Jeremy Brown
 
PDF
How To Become A Good C# Programmer
LearnItFirst.com
 
PDF
Rootcon X - Reverse Engineering Swift Applications
eightbit
 
PPTX
PHP Interview Questions for Freshers 2018
AshokKumar3319
 
PDF
Php Conference Brazil - Phalcon Giant Killer
Jackson F. de A. Mafra
 
PPT
GTU MCA PHP Interview Questions And Answers for freshers
TOPS Technologies
 
API Documentation -- Presentation to East Bay STC Chapter
Tom Johnson
 
PHP Interview Questions and Answers | Edureka
Edureka!
 
T4 presentation
Gary Pedretti
 
Guidelines php 8 gig
Ditinus Technology Pvt LTD
 
Listen and look at your PHP code
Gabriele Santini
 
Object oriented-programming-in-c-sharp
Abefo
 
Hack in the Box GSEC 2016 - Reverse Engineering Swift Applications
eightbit
 
Introduction to c_sharp
HEM Sothon
 
Net serialization
Greg Sohl
 
Php Interview Questions
UmeshSingh159
 
Using Zend_Tool to Establish Your Project's Skeleton
Jeremy Brown
 
How To Become A Good C# Programmer
LearnItFirst.com
 
Rootcon X - Reverse Engineering Swift Applications
eightbit
 
PHP Interview Questions for Freshers 2018
AshokKumar3319
 
Php Conference Brazil - Phalcon Giant Killer
Jackson F. de A. Mafra
 
GTU MCA PHP Interview Questions And Answers for freshers
TOPS Technologies
 
Ad

Viewers also liked (7)

PPT
Blackboard
Derek D'Angelo
 
PPTX
Exporting from data director, Importing into PowerSchool
Derek D'Angelo
 
PPT
Eudora e mail instructions
Derek D'Angelo
 
PPT
Ikeepbookmarks
Derek D'Angelo
 
PPT
Oakland Schools Economics Moodle, Unit 3, Lesson 3 GPI Slides
Derek D'Angelo
 
PPT
Inservice stations
Derek D'Angelo
 
PPT
Oakland Schools Economics Moodle, Unit 3, Lesson 3
Derek D'Angelo
 
Blackboard
Derek D'Angelo
 
Exporting from data director, Importing into PowerSchool
Derek D'Angelo
 
Eudora e mail instructions
Derek D'Angelo
 
Ikeepbookmarks
Derek D'Angelo
 
Oakland Schools Economics Moodle, Unit 3, Lesson 3 GPI Slides
Derek D'Angelo
 
Inservice stations
Derek D'Angelo
 
Oakland Schools Economics Moodle, Unit 3, Lesson 3
Derek D'Angelo
 
Ad

Similar to Zend Framework Workshop (20)

PPT
Demo
bkslide
 
PPT
first pitch
alind tiwari
 
PPT
werwr
alind tiwari
 
PPT
sadasd
alind tiwari
 
PPT
first pitch
alind tiwari
 
PPT
latest slide
alind tiwari
 
PPT
before upload
alind tiwari
 
PPT
ttttt
alind tiwari
 
PPT
before upload
alind tiwari
 
PPT
latest slide
alind tiwari
 
PPT
latest slide
alind tiwari
 
PPT
test
alind tiwari
 
PPT
tiwari
alind tiwari
 
PPT
latest slide
alind tiwari
 
PPT
Test Nan
alind tiwari
 
PPT
tiwari
alind tiwari
 
PPT
Greenathan
alind tiwari
 
PPT
Unit Test for ZF SlideShare Component
zftalk
 
PPT
dfgdf
alind tiwari
 
PPT
Zend Framework Introduction
Rafael Monteiro
 
Demo
bkslide
 
first pitch
alind tiwari
 
sadasd
alind tiwari
 
first pitch
alind tiwari
 
latest slide
alind tiwari
 
before upload
alind tiwari
 
before upload
alind tiwari
 
latest slide
alind tiwari
 
latest slide
alind tiwari
 
tiwari
alind tiwari
 
latest slide
alind tiwari
 
Test Nan
alind tiwari
 
tiwari
alind tiwari
 
Greenathan
alind tiwari
 
Unit Test for ZF SlideShare Component
zftalk
 
Zend Framework Introduction
Rafael Monteiro
 

More from 10n Software, LLC (15)

PPTX
Delaying Gratification: Using queues to build efficient systems
10n Software, LLC
 
PPTX
10 things
10n Software, LLC
 
PPTX
Flex and PHP For the Flash Folks
10n Software, LLC
 
PPTX
PHP Performance: Principles and tools
10n Software, LLC
 
PPTX
Application Deployment with Zend Server 5.5 beta
10n Software, LLC
 
PPTX
Do you queue (updated)
10n Software, LLC
 
PPTX
Flex for php developers
10n Software, LLC
 
PPTX
Creating stunning data analytics dashboard using php and flex
10n Software, LLC
 
PPTX
Php security common 2011
10n Software, LLC
 
PPTX
North east user group tour
10n Software, LLC
 
PPTX
Slideshare - Magento Imagine - Do You Queue
10n Software, LLC
 
PPTX
Do you queue
10n Software, LLC
 
PPTX
Zend Server - OSI Days
10n Software, LLC
 
PPTX
Slides from LAX & DEN usergroup meetings
10n Software, LLC
 
ODP
Flex and Zend Framework
10n Software, LLC
 
Delaying Gratification: Using queues to build efficient systems
10n Software, LLC
 
Flex and PHP For the Flash Folks
10n Software, LLC
 
PHP Performance: Principles and tools
10n Software, LLC
 
Application Deployment with Zend Server 5.5 beta
10n Software, LLC
 
Do you queue (updated)
10n Software, LLC
 
Flex for php developers
10n Software, LLC
 
Creating stunning data analytics dashboard using php and flex
10n Software, LLC
 
Php security common 2011
10n Software, LLC
 
North east user group tour
10n Software, LLC
 
Slideshare - Magento Imagine - Do You Queue
10n Software, LLC
 
Do you queue
10n Software, LLC
 
Zend Server - OSI Days
10n Software, LLC
 
Slides from LAX & DEN usergroup meetings
10n Software, LLC
 
Flex and Zend Framework
10n Software, LLC
 

Recently uploaded (20)

PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 

Zend Framework Workshop

  • 1. Zend Framework WorkshopBy Kevin SchroederTechnology EvangelistZend Technologies
  • 2. About meKevin SchroederTechnology Evangelist for ZendProgrammerSys AdminAuthorIBM i Programmer’s Guide to PHPYou want to do WHAT with PHP? Race Ferraris on the weekendMy Honda has a dismal win record
  • 4. A quick note on Zendcon… BE THERE!!Learn PHP best practices
  • 7. Deploy and scale large PHP applications
  • 8. Explore new technologies like NoSQL and Cloud Computing
  • 9. Learn how to effectively leverage Zend Framework and Zend Framework 2.0What does Zend doZend FrameworkZend Studio (8.0 in public beta 1)Zend ServerMonitoring,Code tracing (freaking cool!!)Job queuingHA Session ClusteringZend Server Cluster ManagerLots and lots of trainingPHP, Zend Framework certifications
  • 10. AgendaThe BasicsIntroductionCoding StandardsInstalling Zend FrameworkAutoloadingZend_SessionZend_ConfigZend_MailZend_ValidateZend_FilterZend_TranslateZend_FormMVCA little more advanced
  • 19. Sample PHP Script<html><head></head><body><?phpfunction questionp($input) { return strrpos ( $input, '?' ) === strlen ( $input ) - 1;}?><?phpif (! isset( $_POST ['submit'] )) {// if the "submit" variable does not exist the form has not been submitted, so display form?><form action="<?phpecho $_SERVER['PHP_SELF']; ?>"method="post">Enter your question: <input name="question" size="50"><input type="submit" name="submit" value="Ask"></form><?php} else {// if the "submit" variable exists the form has been submitted, so look for and process form data,// displaying the resultif(questionp($_POST['question'])) {if(rand(0, 1)): echo 'yes'; else: echo 'no'; endif;} else {echo 'Don\'t you know what a question is?'; }}?PHP: Past and Present| 8
  • 20. Anatomy of a PHP ApplicationPHP: Past and PresentPresentationApplication ControlDatabase AccessBusiness LogicPresentationApplication ControlBusiness LogicPresentation| 9
  • 21. Anatomy of a PHP ApplicationPHP: Past and Presentindex.php3index.php3index.php3index.php| 10
  • 22. Anatomy of a PHP ApplicationPHP: Past and Presentindex.php3index.php3index.php3index.phpindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php| 11
  • 23. Anatomy of a PHP ApplicationPHP: Past and Presentindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.phpindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.phpindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.phpindex.php3index.php3index.php3index.php3index.php3index.php3index.php| 12
  • 24. Anatomy of a PHP ApplicationPHP: Past and Presentindex.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3index.php3| 13|
  • 25. Anatomy of a Modern PHP Application | 22-Sep-10PHP: Past and PresentPresentationSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlSomething.phtmlApplication ControlSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpBusiness LogicSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpDatabase AccessSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.phpSomething.php| 14
  • 26. Zend FrameworkMake everything as simple as possible, but no simpler. - Albert Einstein
  • 27. PHP ProblemsHow can we promote reuse and standards in a strong culture of decentralization?How can we propagate best practices across a community of cowboy coders numbering in the millions?How do we manage the newfound complexity of large PHP applications?How do we promote integration with commercial technologies in a community that has been developed in parallel to these technologies?How do we write better PHP applications? | 22-Sep-10Name of this section| 16
  • 28. The Answer?Name of this section| 17
  • 29. What is Zend Framework?An open source, MVC-based, full-featured PHP frameworkA set of use-at-will components; a component libraryA vehicle through which Zend disseminates best practicesA communityA philosophyA standardA gateway to the larger PHP community | 22-Sep-10PHP: Past and Present| 18
  • 30. What sets ZF apart?High quality code; all components have unit test coverage of > 80% (both lines and branches) and the tests are run against the framework continuouslyA use-at-will architecture that allows developers to mix and match their favorite technologiesA contribution process that both guarantees quality and encourages active community contributions while protecting against intellectual property claimsWe only tackle problems when we can bring value that isn’t currently available in the PHP communityWe believe that web services must be first-class citizens for today’s Web 2.0 applications | 22-Sep-10PHP: Past and Present| 19
  • 32. Supported by All Popular PHP IDEs
  • 33. Over 50 Books Written
  • 34. 74% of all Zend Framework Applications are Business-Critical* Zend Framework Developer Survey, Dec. 2009
  • 35. Dojo Integration+In May, 2008 Zend announced a collaboration between the Zend Framework and Dojo Toolkit projects. Zend Framework 1.6 contains the first integration points between these 2 projects:JSON-RPC Serverdojo.data EnvelopesDojo View HelperDijit integration with Zend_Form & Zend_ViewDojo Library Re-distribution
  • 36. Autumn, 2008Download & InstallZend FrameworkDownload the latest version of Zend Framework and extract the contents of the library folder to your project's library directoryhttp://framework.zend.com/downloadYou should now find the top-level Zend directory which contains all Zend Framework components under your library directoryThat's it! Zend Framework is now installed and ready to use
  • 37. Autumn, 2008What’s in Zend Framework?Simple, convenient object-oriented solutions to common web application development tasks:MVC web app framework(model-view-controller)Database accessLucene-compatible Search engineInput filtering and validationAuthenticationAccess controlSession handlingI18N, locales, translationPDF file reading and writingHTTP clientForm HandlingXML-RPCREST web servicesRSS and Atom feedsLoggingMail reading and sendingCachingConfiguration filesCommand-line option parsingMUCH, MUCH more!
  • 40. Don’t start with MVC firstThere are MANY libraries that you can utilize firstA trustworthy saying“Don’t use a framework until you know why you need a framework”Don’t use MVC until you know you need MVCOr have at least experienced the pain of managing a large application without it
  • 41. Things to knowAll ZF-based classes start with Zend_If you build a library that utilizes ZF, do not prefix your classes with that (breaks coding standards)Use the autoloaderUse plugin loadersStart small
  • 42. Coding StandardsFiles with ONLY PHP code start with <?php and have no closing tagIndentation uses 4 spaces, tabs not allowedLines end with Unix EOLClass naming standards changed after 1.9 to prepare for PHP 5.3 and ZF 2Function/method declarations Anything marked private/protected is prefaced with an underscore (private $_var = null)Numbers are permitted in variable/method/function names, but are not recommended
  • 43. Coding StandardsGlobally defined variables/functions are allowed, but not recommended (use registry/static methods instead)Variables/methods/functions are named using camelCaseThere is some debate one what a camel looks like when using an acronym (e.g. PDF)Global constants are allowed, but discouraged. Use class constants insteadClass constants should be UPPER_CASE_WITH_UNDERSCORE“Variable substitution is {$allowed} but not ${allowed}”‘If no variable substitution is needed then use single quotes’For arrays, negative index keys are not allowed
  • 44. Coding StandardsOne class per fileBracesFinal brace is always on its own lineMethod/function calls start on the next lineConditional statements/loops start on the same lineBreak clauses MUST have a defaultAll functions/methods/class members MUST have a PHPDoc blockRead the coding standards at http://framework.zend.com/ in the docs
  • 45. How to start?Start simple, use utility classesZend_LoaderZend_DateZend_ConfigZend_SessionZend_TranslateZend_ValidateZend_FilterZend_Form (!)Others
  • 47. Zend_LoaderUsed to include files for classes that have not been loaded yetIt searches the include_path for the requested class Two types of loadersAutoloaderJust a standard autoloaderPluginLoaderUsed for loading classes based off of a prefix
  • 48. Zend_Loader_AutoloaderInitializeZend_Loader_Autoloader::getInstance();Register pseudo namespaceZend_Loader_Autoloader::getInstance() ->registerNamespace('Myapp_');Set the autoloader for all namespacesZend_Loader_Autoloader::getInstance() ->setFallbackAutoloader(true);
  • 49. Zend_Loader_PluginloaderUsed to load named classes, not autoloadUsed extensively by several ZF components
  • 50. Zend_Loader_Pluginloader/library/MyApp/MyComponent/Classone.php/library/MyApp/AnotherComponent/Classtwo.php$loader = new Zend_Loader_PluginLoader();$loader->addPrefixPath( 'MyApp_MyComponent', 'MyApp/MyComponent');$loader->addPrefixPath( 'MyApp_AnotherComponent', 'MyApp/AnotherComponent');
  • 52. Zend_SessionUse this instead of $_SESSION. Why?Works much better for complex applicationsAllows for easier separation of components$ns = new Zend_Session_Namespace('Component-1');$ns = new Zend_Session_Namespace('Component-2');
  • 53. Zend_SessionGood API (standard session ext has very minimal API)public function lock();public function unlock();public function apply($callback);public function applySet($callback);public functionsetExpirationSeconds( $seconds, $variables = null);public function setExpirationHops( $hops, $variables = null, $hopCountOnUsageOnly = false);
  • 54. Zend_ConfigProvides a way of dealing with configurationA consistent API for getting and setting valuesImplements Countable, Iterator (uses SPL)Existing mechanismsPHP Arrays (great with opcode caches)INI FilesXML FilesYour own (Don’t use the DB)
  • 55. Zend_ConfigGenerally used forDatabase adapter credentialsCaching optionsPathsZend_Application uses a LOT of configuration
  • 56. Using Zend ConfigYou can retrieve data by section
  • 57. Using Zend_ConfigYou can have inheritance between sectionsBest practice: inherit from [production]
  • 58. Zend_ValidateUsed to provide integratable validation toolingDon’t build it yourself!!Some example validatorsEmail AddressCredit CardString LengthHost nameAnd about 80 othersChainable using new Zend_Validate()
  • 59. Zend_Validate – Building your ownMust implement Zend_Validate_InterfaceZend_Validate_Abstract is a better choice to extendConstructor is optional, used for passing options
  • 60. Zend_FilterUsed to filter dataSome examplesHtmlEntitiesEncrypt/DecryptStripTagsStripNewLines
  • 61. Zend_FormNew to ZF 1.5 (one of the best features)HandlesRendering the formEscaping your outputFiltering your inputValidating your data
  • 62. Zend_Form – Simple usage$form = new Zend_Form();$form->setMethod('POST');$form->setAction('/submitform.php');$form->setView(new Zend_View());$form->addElement('text', 'email');$form->addElement('text', 'name');$form->addElement('submit', 'submit');echo $form;
  • 63. Zend_Form – Less simple usageForms and form elements have a LOT of options$form->addElement( 'text', 'email', array( 'label' => 'Email', 'required' => true ));
  • 64. Zend_Form – Adding validators$form->addElement( 'text', 'email', array( 'label'=> 'Email', 'required'=> true, 'validators'=> array( 'EmailAddress' ) ));Don’t use validator objects; name them insteadBut make sure to test that they work
  • 65. Zend_Form – Adding filters$form->addElement( 'text', 'name', array( 'label'=> 'Name', 'required'=> true, 'filters'=> array( 'Alpha' ) ));
  • 66. Zend_Form - trickAll of the configuration parameters are passed to getters and settersWant to know what configuration options are available? Look at the setterssetLabel() = array(‘label’ => ‘name’)setValidators()setName()setOrder()setRequired()
  • 67. Zend_Form – Architecting your appBest practicesSubclass Zend_FormVery reusableVery testableCreate forms to match your existing data structureHave pre-defined forms that match up to existing modelsLet the designers worry about layoutZend_Form allows for CSS heavy design (ok, that’s good and bad )
  • 68. Zend_Form – Architecting your appIf using with MVCPlace in /application/formsPreface with Form_Use a plugin loaderIf notPlace it in a standard library path and use the autoloader
  • 69. Zend_LogConceptsLogger – usually an instance of Zend_LogWriter – the mechanism which writes the log entry to the storage mediumMust extend Zend_Log_Writer_AbstractFilter – used to determine IF a log entry should be sent to the writerMust implement Zend_Log_Filter_InterfaceFormatter – creates the text string that will be sent to the writer
  • 70. Zend_LogSeveral logging levels (BSD syslog)EMERG - Emergency: system is unusableALERT - Alert: action must be taken immediatelyCRIT - Critical: critical conditionsERR - Error: error conditionsWARN - Warning: warning conditionsNOTICE - Notice: normal but significant conditionINFO - Informational: informational messagesDEBUG - Debug: debug messages
  • 71. Zend_LogAvailable writersDbFirebugMailMockCan write to multiple writers at a timeEach writer can have multiple filtersNull
  • 75. MVCModelAn object that represents a unit of data/functionalityViewThe user interfaceControllerWhere your business logic lies
  • 76. MVCIt’s best to not use “pure” MVCUse the “thin controller” architecturePlace as much of your business logic in the model as possibleReduces code duplicationEnhances code testability
  • 77. Zend_ControllerComponent where the Controller portion of MVC residesSeveral conceptsFront ControllerAction ControllerPluginsHelpers
  • 78. Zend_Controller – Start to finishFront controllerRouterDispatcherAction controller
  • 79. MVC Request Lifecycledispatch() – Starts the dispatch processrouteStartup() – Called prior to parsing the URL for the requestrouteShutdown() – Called immediately after the module, controller and action have been determineddispatchLoopStartup() – Called immediately before the dispatch loop startspreDispatch() – Called at the beginning of each dispatch loop
  • 80. MVC Request Lifecycleinit() – Called from inside the controller’s constructorpreDispatch() – Called for each action helper that is currently initializedpreDispatch() – A hook on the current controller object *Action() – The individual action that was requested during the routing processpostDispatch() – A hook in the current controller object
  • 81. MVC Request LifecyclepostDispatch() – Called for each loaded action helperpostDispatch() – Called for each plugindispatchLoopShutdown() – The last hook to be executed
  • 82. Front ControllerThe “access point” for the application
  • 83. Action ControllersExtends Zend_Controller_ActionAccess $_GET, $_POST via request objectPass output/headers to response object
  • 84. Accessing an action controller
  • 85. Controller PluginsAllows you to execute functionality at some point along the execution chainPlugins are typically not interactive like helpersNeed to extend Zend_Controller_Plugin_Abstract
  • 87. ControllerPlugin - Exampleclass Esc_Application_Plugin_Maintenance extends Zend_Controller_Plugin_Abstract{ public function routeShutdown(Zend_Controller_Request_Abstract $request) { $request->setActionName('index'); $request->setModuleName('default'); $request->setControllerName('maintenance'); } }
  • 88. Controller HelpersInject on-demand functionality into action controllersCacheContext Switching (“Do I use HTML, JSON, XML?”)View RendererBuild your ownMinimize the need to extend Zend_Controller_ActionHas init(), preDispatch(), postDispatch() hooksOnly called if a helper object has been instantiated
  • 89. Controller Helpers – Building your ownMust extend Zend_Controller_Action_Helper_AbstractMust be registered with the helper brokerZend_Controller_Action_HelperBroker::addPath( APPLICATION_PATH.'/helpers', 'Helper');Call from the controller$this->_helper->Sendemail( 'Kevin Schroeder', '[email protected]', 'We did something in the last request');
  • 90. Zend_ViewUsed to handle the view (user interface) from BLOlder style apps have the two mixedCan be used separately from MVC (if you like)Useful if you want to re-use view helpers or form componentsIf using MVC, generally stored in controllers/../views/script
  • 91. Zend_View – Step 1: Assigning data$data = array( array( 'author' => 'Kevin Schroeder', 'title' => 'The IBM i Programmer\'s Guide to PHP' ), array( 'author' => 'Kevin Schroeder', 'title' => 'You want to do WHAT with PHP?' ));Zend_Loader::loadClass('Zend_View');$view = new Zend_View();$view->books = $data;echo $view->render('booklist.php');
  • 92. Zend_View – Step 2: Rendering data<?php if ($this->books): ?> <table> <tr> <th>Author</th> <th>Title</th> </tr> <?phpforeach ($this->books as $key => $val): ?> <tr> <td><?php echo $this->escape($val['author']) ?></td> <td><?php echo $this->escape($val['title']) ?></td> </tr> <?phpendforeach; ?> </table><?php else: ?><p>There are no books to display.</p><?phpendif;?>
  • 93. Using the ViewRendererAn action helper that is loaded by defaultExecutes in the postDispatch() hookExamines the controller/action combination and automatically runs the proper view scriptIndexController::indexAction()/views/scripts/index/index.phtml
  • 94. View HelpersView helpers make your life easierUsed to provide additional functionality similar to an action helper, but for the viewReferenced via the $this object when in a viewLoaded using a plugin loaderUsed to keep logic out of the view (very important)Try to limit views to if and foreach statements
  • 95. View Helpers ExamplesEasy translation integrationecho $this->translate('Hello World');Capturing JS so it can be output elsewhere<?php $this->headScript()->captureStart(); ?>alert('Hello World');<?php $this->headScript()->captureEnd(); ?>
  • 96. View HelpersYou can build your own!Does not need to implement any interface or abstract classGenerally placed in /views/helpers (configurable)Must have a method name defined as the same name of the classMy_Helper_Sendemail must have a method called sendemail().class My_Helper_Sendemail{ public function sendemail($to, $subject, $message) { // Haven't gotten to Zend_Mail yet :-) mail($to, $subject, $message); }}
  • 97. Using PartialsPartials are used to render small, re-usable portions of the viewHandled via a view helperPartialPartialLoopVery useful for any iterative functionalityArraysZend_Db_Table_RowsetAnything implementing the Iterator interface
  • 98. The ModelUnlike other frameworks it is any class that represents your data or business logicCould be a service objectCould be a text fileCould be an LDAP entryCould be a Zend_Db object
  • 99. Zend_DbDatabase abstraction layer (as opposed to access abstraction layer)Several different database vendors are supportedAbstractions for common functionality such as select, insert, update, delete, limit, offset or transactionsConnects to the database on demandAdapter instance is usually created via Zend_Db::factory()Integrated database profiling
  • 100. Zend_Db_SelectProvides a vendor-independent mechanism for creating select statementsVery useful, but be careful of the unintended consequences of abstraction$select->from('table') ->where('table_id = ?', $_GET[‘val']);Output: SELECT `table`.* FROM `table` WHERE (table_id = ?)Supports multiple join types, where, group by, order, etc.
  • 101. ORMUses the Table/Row Data Gateway Design PatternsOne class to represent the tableOne class to represent a row in the table
  • 102. ORM – The TableTable classes extend Zend_Db_Table_AbstractHandles references to other tables class Model_DbTable_Comment extends Zend_Db_Table_Abstract{ protected $_name = 'comment'; protected $_rowClass = 'Model_Comment'; protected $_referenceMap = array( 'Content' => array( 'columns' => 'content_key', 'refTableClass' => 'Model_DbTable_Content', 'refColumns' => 'content_key' ), );}
  • 103. ORM – The RowModel classes extend Zend_Db_Table_Row_Abstractclass Model_City extends Zend_Db_Table_Row_Abstract{}Row data is accessed via a __get callGood idea to use getters and setters to access them(great for code completion)
  • 104. Fetching Data$dbTable = new Model_DbTable_Comment();$comment = $dbTable->find($_GET['id']);$dbTable = new Model_DbTable_Comment();$select = $dbTable->select() ->where('active = ?', $_GET['active']);$comment = $dbTable->fetchRow()->current();
  • 105. ORM - RelationshipsRetrieve an instance of the row classCall a wacked method call which calls __call() and figures out which db table object to load and query on.class Model_DbTable_Comment extends Zend_Db_Table_Abstract{ protected $_name = 'comment'; protected $_rowClass = 'Model_Comment'; protected $_referenceMap = array( 'Content' => array( 'columns' => 'content_key', 'refTableClass' => 'Model_DbTable_Content', 'refColumns' => 'content_key' ), );}
  • 106. Calling a related object$tabs = $comment ->findModel_DbTable_TagViaModel_DbTable_TagContent();Write a getter that defines that in your modelclass Model_Content extends Esc_ModelAbstract{ public function getTags() { return $this ->findModel_DbTable_TagViaModel_DbTable_TagContent() }}
  • 108. Unit TestingWhy Unit Test?Simplify maintenanceIt defines expectations It describes behaviors identified by the application It tells us when new changes break existing code and behaviors
  • 109. TermsUnitThe piece of code you are testingTestA piece of code that calls the piece of code you’re testingAssertionValidating return types or results of the testCode CoverageA report on which lines of code have been testedUsed to determine additional tests that need to be writtenContinuous IntegrationThe continuous application of quality control, i.e. unit tests
  • 110. Testing the modelThe easiest of allTest classes typically extend PHPUnit_Framework_TestCase
  • 111. Testing the controllerSetting up the testTest class extends Zend_Test_PHPUnit_ControllerTestCaseIf testing Zend_Application make sure you add the bootstrap in the setUp() methodMake sure you reset() your testsResponseRequestLayoutHelper Broker
  • 112. Testing the controllerYou can testRouting (also good for checking authorization)Response codesOutput (we’ll look at that next)
  • 113. Testing the viewBest tested through the controllerDefine which HTML elements need to be present on the page and verify that they exist or have certain valuesCan be done usingCSS SelectorsXpath Queries
  • 114. Zend_LayoutImplements Two Step View patternSame name as a dance in Texas, but that’s not important
  • 115. A little more advanced…
  • 116. Zend_ApplicationUsed for defining an application contextZend_Controller_Front just handled the brokering of the requestZend_Application handles Bootstrapping (dev/testing/staging/production)Creating the autoloaderDispatchingResource creation
  • 117. BootstrappingImplements Zend_Application_Bootstrap_BootstrapperUsed to bootstrap (set up the environment) and then execute the requestMost applications can simply extend Zend_Application_Bootstrap_BootstrapThis is what we will assume you are using
  • 118. BootstrappingResource methodsUse the resource autoloader Zend_Application_Module_Autoloader placed in _initAutoload()OrderZend_Application::bootstrap()Bootstrap class instantiatedAny methods starting with _init() are called and the return value is placed in a containerAction retrieves the resource through calling getInvokeArg() and naming the resource
  • 119. BootstrappingBootstrap class is instantiated every time so DON’T put everything there (horrible for performance, PHP loves lazy loading)One option is to override hasResource() method in Bootstrap so that it instantiates a resource only when it is neededBest practice? Don’t know. Kevin’s practice? Yes. Therefore it is good
  • 120. ResourcesPluggable pieces of functionality tied to the applicationTies functionality directly in with the configurationSample of existing pluginsCachemanagerDbLogFrontcontrollerTranslate
  • 122. Service TheoryMany services have a very similar execution flowReceive requestFind class that can service the requestInstantiate object that can handle the requestReturn result to clientWhy re-invent the wheel?
  • 123. Zend_ServerBase component for several service-oriented componentsPrimarily used for reflection and a standard interfaceActual implementation is left to component
  • 124. Zend_*_ServerSeveral components implement Zend_Server_AbstractUseful for standardized web service implementationforeach (glob(APPLICATION_PATH.'/mappers/*.php') as $dir) {$name = substr(basename($dir), 0, -4); $class = 'Mapper_' . $name; $serviceHandler->setClass($class, $name);}echo $serviceHandler->handle();Using data mappers are your key to happiness$serviceHandler = new Zend_Json_Server();$serviceHandler = new Zend_Amf_Server();$serviceHandler = new Zend_Xml_Server();
  • 125. Writing Re-usable ModelsWrite your application logic once, but use it in many different waysWhy? MVC is only one consumerCan be called by job scripts, message systems, queues, etc.Service endpoints can act as consumers(Hint: JSON-RPC is a good way to feed your Ajax applications)112
  • 127. The individual resources and units of work in your application
  • 128. E.g. user, team, backlog, sprint, etc.
  • 129. E.g., object relations, transactions, queries
  • 131. Public API of the application; i.e., the behaviors you wish to expose
  • 132. Logic for injecting dependenciesService Layer in Perspective
  • 133. Benefits to Service LayersAllows easy consumption of the application via your MVC layer
  • 134. Allows easy re-use of your application via services
  • 135. Write CLI scripts that consume the Service LayerWhat kind of application logic?Validation and filtering
  • 137. Transactions and interactions between model entitiesclassPersonService{ publicfunctioncreate(array$data){$person=newPerson();if(!$data=$this->getValidator()->isValid($data)) { throw newInvalidArgumentException();}$person->username=$data['username'];$person->password=$data['password'];$person->email=$data['email'];$this->getMapper()->save($person);return$person;}}117
  • 138. Return objects implementing __toString() and/or toArray()Easily converted to a variety of formats for your XHR clients
  • 141. Strings and arrays serialize and deserialize easilyReturning dataclass Foo{ public function __toString() { return 'foo'; } public function toArray() { $array = array();foreach ($this->_nodes as $node) { $array[] = $node->name; } return $array; }}119
  • 142. Zend_JsonUseful for encoding/decoding data$data = range(1, 20);echo Zend_Json::encode($data);mehZend_Json_Server is neatoJSON-RPC implementationSupported byDojoJquery (via plugin)Several more
  • 143. Zend_JsonServer Side$serviceHandler = new Zend_Json_Server();$serviceHandler->setClass('Peaks');echo $serviceHandler->handle();Client Sidedojo.require("dojo.io.script");dojo.require("dojo.rpc.JsonService");dojo.addOnLoad(function(){rpc = new dojo.rpc.JsonService("/json-rpc", "Peaks"); call = rpc["Peaks.getStates"]().addCallback( function(data) {/*todo*/});});
  • 144. Zend_AmfAMF = Action Message FormatProprietary, Open Spec protocol developed by AdobeUsed primarily for implementing a service that communicates with Flash applicationsZend_Amf_Server extends Zend_Server_AbstractWorks well with switching between JSON, XML-RPCAMF supports typed parameters and return valuesSetting up an AMF interface in Flash Builder/Zend Studio
  • 145. Zend_Service_TwitterStupid easy Twitter access$twitter = new Zend_Service_Twitter( 'mytwitterusername', 'password‘);$response = $twitter->status->update( 'OSI Days Rocks!‘);
  • 146. Zend_Service_TwitterPublic API calls often don’t even require authentication$ts = new Zend_Service_Twitter_Search('json');$res = $ts->search($this->_search, array( 'since_id'=> (int)$id ));$text = array();foreach ($res['results'] as $result) { $text[] = $result['text'];}
  • 148. What will ZF 2 be like?GoalsEase the learning curveMake extending the framework trivially simpleImprove baseline performance of the frameworkSimplify maintenance of the frameworkBe an exemplar of PHP 5.3 usageProvide mechanisms for using just the parts of the framework needed
  • 149. What will ZF 2 be like?RoadmapStandardized Option KeysExceptions. Each component will have it's own Exception interfaceDesign By ContractElimination of most singletonsCreate general-purpose, cross-functional components to reduce duplicate codeUsage of new language features within plugin architectures, specifically __invoke() and closures
  • 150. What will ZF 2 be like?Roadmap (con’t)Autoload-only. Full use of Namespaces. goto. (usage of goto will be evaluated on a case-by-case basis)
  • 151. What will ZF 2 be like?Should you be thinking about ZF2?Not yet
  • 154. Get this information and all the examples at eschrade.com…
  • 155. Remember… BE THERE!!Learn PHP best practices
  • 158. Deploy and scale large PHP applications
  • 159. Explore new technologies like NoSQL and Cloud Computing
  • 160. Learn how to effectively leverage Zend Framework and Zend Framework 2.0