Zend Framework Workshop

Post on 17-May-2015

1.039 views 0 download

Tags:

description

Slides from the Zend Framework workshop I did at OSIdays in Chennai, India

Transcript of Zend Framework Workshop

©All rights reserved. Zend Technologies, Inc.

Zend Framework Workshop

By Kevin Schroeder

Technology Evangelist

Zend Technologies

©All rights reserved. Zend Technologies, Inc.

About me

• Kevin Schroeder Technology Evangelist for Zend

Programmer

Sys Admin

Author• IBM i Programmer’s Guide to PHP

• You want to do WHAT with PHP?

Race Ferraris on the weekend• My Honda has a dismal win record

©All rights reserved. Zend Technologies, Inc.

Follow us! Zend Technologies

http://twitter.com/zend

http://twitter.com/kpschrade (me!)

www.eschrade.com

©All rights reserved. Zend Technologies, Inc.

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

©All rights reserved. Zend Technologies, Inc.

What does Zend do

• Zend Framework

• Zend Studio (8.0 in public beta 1)

• Zend Server Monitoring,

Code tracing (freaking cool!!)

Job queuing

HA Session Clustering

• Zend Server Cluster Manager

• Lots and lots of training

• PHP, Zend Framework certifications

©All rights reserved. Zend Technologies, Inc.

Agenda

• The Basics Introduction Coding Standards Installing Zend

Framework Autoloading Zend_Session Zend_Config Zend_Mail Zend_Validate Zend_Filter Zend_Translate Zend_Form MVC

•A little more advanced

• Zend_Application

• Zend_Db

• Table/Row Data Gateway

•Services

• Theory

• Zend_Json_Server

• Zend_Amf

• Zend_Service_Twitter

©All rights reserved. Zend Technologies, Inc.

Why do we use PHP?

©All rights reserved. Zend Technologies, Inc.

Sample PHP Script

<html>

<head></head>

<body>

<?php

function questionp($input) {

return strrpos ( $input, '?' ) === strlen ( $input ) - 1;

}

?>

<?php

if (! isset ( $_POST ['submit'] )) {

// if the "submit" variable does not exist the form has not been submitted, so display form

?>

<form action="<?php echo $_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 result

if(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

©All rights reserved. Zend Technologies, Inc.

Anatomy of a PHP Application

PHP: Past and Present

| 9

Presentation

Application Control

Database Access

Business Logic

Presentation

Application Control

Business Logic

Presentation

©All rights reserved. Zend Technologies, Inc.

Anatomy of a PHP Application

PHP: Past and Present

| 10

index.php3

index.php3

index.php3

index.php

©All rights reserved. Zend Technologies, Inc.

Anatomy of a PHP Application

PHP: Past and Present

| 11

index.php3

index.php3

index.php3

index.php

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3index.php3

index.php3

index.php3

index.php

©All rights reserved. Zend Technologies, Inc.

Anatomy of a PHP Application

PHP: Past and Present

| 12

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3index.php3

index.php3

index.php3

index.php

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3index.php3

index.php3

index.php3

index.php

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3index.php3

index.php3

index.php3

index.php

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php

©All rights reserved. Zend Technologies, Inc.

Anatomy of a PHP Application

PHP: Past and Present

| 13

|

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3 index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

index.php3

©All rights reserved. Zend Technologies, Inc.

Anatomy of a Modern PHP Application

| Apr 12, 2023

PHP: Past and Present

| 14

Presentation

Database Access

Business Logic

Application Control

Something.phtml

Something.phtml

Something.phtml

Something.phtml

Something.phtml

Something.phtml

Something.phtml

Something.phtml

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

Something.p

hp

©All rights reserved. Zend Technologies, Inc.

Make everything as simple as possible, but no simpler.

- Albert Einstein

Zend Framework

©All rights reserved. Zend Technologies, Inc.

PHP Problems

• How 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?

| Apr 12, 2023

Name of this section

| 16

©All rights reserved. Zend Technologies, Inc.

The Answer?

Name of this section

| 17

©All rights reserved. Zend Technologies, Inc.

What is Zend Framework?

• An open source, MVC-based, full-featured PHP framework

• A set of use-at-will components; a component library

• A vehicle through which Zend disseminates best practices

• A community

• A philosophy

• A standard

• A gateway to the larger PHP community

| Apr 12, 2023

PHP: Past and Present

| 18

©All rights reserved. Zend Technologies, Inc.

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 continuously

• A use-at-will architecture that allows developers to mix and match their favorite technologies

• A contribution process that both guarantees quality and encourages active community contributions while protecting against intellectual property claims

• We only tackle problems when we can bring value that isn’t currently available in the PHP community

• We believe that web services must be first-class citizens for today’s Web 2.0 applications

| Apr 12, 2023

PHP: Past and Present

| 19

©All rights reserved. Zend Technologies, Inc.

Our Technology Partners

… and more

©All rights reserved. Zend Technologies, Inc.

Supported by All Popular PHP IDEs

©All rights reserved. Zend Technologies, Inc.

Over 50 Books Written

©All rights reserved. Zend Technologies, Inc.

74% of all Zend Framework Applications are Business-Critical

* Zend Framework Developer Survey, Dec. 2009

©All rights reserved. Zend Technologies, Inc.

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 Server

• dojo.data Envelopes

• Dojo View Helper

• Dijit integration with Zend_Form & Zend_View

• Dojo Library Re-distribution

+

©All rights reserved. Zend Technologies, Inc.Autumn, 2008

Download & Install Zend Framework• Download the latest version of Zend Framework and extract the contents of the library folder to your project's library directory

http://framework.zend.com/download

• You should now find the top-level Zend directory which contains all Zend Framework components under your library directory

• That's it! Zend Framework is now installed and ready to use

©All rights reserved. Zend Technologies, Inc.Autumn, 2008

What’s in Zend Framework?

MVC web app framework(model-view-controller)

Database access

Lucene-compatible Search engine

Input filtering and validation

Authentication

Access control

Session handling

I18N, locales, translation

PDF file reading and writing

HTTP client

Form Handling

XML-RPC

REST web services

RSS and Atom feeds

Logging

Mail reading and sending

Caching

Configuration files

Command-line option parsing

MUCH, MUCH more!

• Simple, convenient object-oriented solutions to common web application development tasks:

©All rights reserved. Zend Technologies, Inc.Autumn, 2008

Zend Framework Overview

© 2009 All rights reserved. Zend Technologies, Inc.

WHERE TO START

• Don’t start with MVC first• There are MANY libraries that you can utilize first• A trustworthy saying

“Don’t use a framework until you know why you need a framework”

• Don’t use MVC until you know you need MVC Or have at least experienced the pain of managing a large

application without it

Things to know

• All 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 autoloader• Use plugin loaders• Start small

Coding Standards

• Files with ONLY PHP code start with <?php and have no closing tag

• Indentation uses 4 spaces, tabs not allowed• Lines end with Unix EOL• Class naming standards changed after 1.9 to prepare for

PHP 5.3 and ZF 2• Function/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 Standards

• Globally defined variables/functions are allowed, but not recommended (use registry/static methods instead)

• Variables/methods/functions are named using camelCase There 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 instead

• Class 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 Standards

• One class per file• Braces

Final brace is always on its own line Method/function calls start on the next line Conditional statements/loops start on the same line

• Break clauses MUST have a default• All functions/methods/class members MUST have

a PHPDoc block• Read the coding standards at

http://framework.zend.com/ in the docs

How to start?

• Start simple, use utility classes Zend_Loader Zend_Date Zend_Config Zend_Session Zend_Translate Zend_Validate Zend_Filter Zend_Form (!) Others

© 2009 All rights reserved. Zend Technologies, Inc.

UTILITY CLASSES

Zend_Loader

• Used to include files for classes that have not been loaded yet

• It searches the include_path for the requested class

• Two types of loaders Autoloader

• Just a standard autoloader PluginLoader

• Used for loading classes based off of a prefix

Zend_Loader_Autoloader

• Initialize• Zend_Loader_Autoloader::getInstance();• Register pseudo namespace• Zend_Loader_Autoloader::getInstance() ->registerNamespace('Myapp_');

• Set the autoloader for all namespaces• Zend_Loader_Autoloader::getInstance() ->setFallbackAutoloader(true);

Zend_Loader_Pluginloader

• Used to load named classes, not autoload• Used 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_Session

• Use this instead of $_SESSION. Why?• Works much better for complex applications• Allows for easier separation of components

$ns = new Zend_Session_Namespace('Component-1');

$ns = new Zend_Session_Namespace('Component-2');

Zend_Session

• Good API (standard session ext has very minimal API)

public function lock();public function unlock();public function apply($callback);public function applySet($callback);public function setExpirationSeconds( $seconds, $variables = null);public function setExpirationHops( $hops, $variables = null, $hopCountOnUsageOnly = false);

Zend_Config

• Provides a way of dealing with configuration• A consistent API for getting and setting values• Implements Countable, Iterator (uses SPL)• Existing mechanisms

PHP Arrays (great with opcode caches) INI Files XML Files Your own (Don’t use the DB)

Zend_Config

• Generally used for Database adapter credentials Caching options Paths

• Zend_Application uses a LOT of configuration

Using Zend Config

• You can retrieve data by section

Using Zend_Config

• You can have inheritance between sections

• Best practice: inherit from [production]

Zend_Validate

• Used to provide integratable validation tooling Don’t build it yourself!!

• Some example validators Email Address Credit Card String Length Host name And about 80 others

• Chainable using new Zend_Validate()

Zend_Validate – Building your own

• Must implement Zend_Validate_Interface• Zend_Validate_Abstract is a better choice to

extend• Constructor is optional, used for passing options

Zend_Filter

• Used to filter data• Some examples

HtmlEntities Encrypt/Decrypt StripTags StripNewLines

Zend_Form

• New to ZF 1.5 (one of the best features)• Handles

Rendering the form Escaping your output Filtering your input Validating 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 usage

• Forms 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 instead

But 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 - trick

• All of the configuration parameters are passed to getters and setters

• Want to know what configuration options are available? Look at the setters setLabel() = array(‘label’ => ‘name’) setValidators() setName() setOrder() setRequired()

Zend_Form – Architecting your app

• Best practices Subclass Zend_Form

• Very reusable• Very testable

Create forms to match your existing data structure• Have pre-defined forms that match up to existing models

Let the designers worry about layout• Zend_Form allows for CSS heavy design (ok, that’s good and

bad )

Zend_Form – Architecting your app

• If using with MVC Place in /application/forms Preface with Form_ Use a plugin loader

• If not Place it in a standard library path and use the autoloader

Zend_Log

• Concepts Logger – usually an instance of Zend_Log Writer – the mechanism which writes the log entry to the

storage medium• Must extend Zend_Log_Writer_Abstract

Filter – used to determine IF a log entry should be sent to the writer

• Must implement Zend_Log_Filter_Interface Formatter – creates the text string that will be sent to the

writer

Zend_Log

• Several logging levels (BSD syslog)

EMERG - Emergency: system is unusable

ALERT - Alert: action must be taken immediately

CRIT - Critical: critical conditions

ERR - Error: error conditions

WARN - Warning: warning conditions

NOTICE - Notice: normal but significant condition

INFO - Informational: informational messages

DEBUG - Debug: debug messages

Zend_Log

• Available writers• Db• Firebug• Mail• Mock

• Can write to multiple writers at a time• Each writer can have multiple filters

•Null•Stream•Syslog•ZendMonitor

© 2009 All rights reserved. Zend Technologies, Inc.

MVC

©All rights reserved. Zend Technologies, Inc.

MVC

• Model An object that represents a unit of data/functionality

• View The user interface

• Controller Where your business logic lies

©All rights reserved. Zend Technologies, Inc.

MVC

• It’s best to not use “pure” MVC

• Use the “thin controller” architecture

• Place as much of your business logic in the model as possible

• Reduces code duplication

• Enhances code testability

©All rights reserved. Zend Technologies, Inc.

Zend_Controller

• Component where the Controller portion of MVC resides

• Several concepts Front Controller

Action Controller

Plugins

Helpers

©All rights reserved. Zend Technologies, Inc.

Zend_Controller – Start to finish

• Front controller

• Router

• Dispatcher

• Action controller

©All rights reserved. Zend Technologies, Inc.

MVC Request Lifecycle

• dispatch() – Starts the dispatch process

• routeStartup() – Called prior to parsing the URL for the request

• routeShutdown() – Called immediately after the module, controller and action have been determined

• dispatchLoopStartup() – Called immediately before the dispatch loop starts

• preDispatch() – Called at the beginning of each dispatch loop

©All rights reserved. Zend Technologies, Inc.

MVC Request Lifecycle

• init() – Called from inside the controller’s constructor

• preDispatch() – Called for each action helper that is currently initialized

• preDispatch() – A hook on the current controller object

• *Action() – The individual action that was requested during the routing process

• postDispatch() – A hook in the current controller object

©All rights reserved. Zend Technologies, Inc.

MVC Request Lifecycle

• postDispatch() – Called for each loaded action helper

• postDispatch() – Called for each plugin

• dispatchLoopShutdown() – The last hook to be executed

©All rights reserved. Zend Technologies, Inc.

Front Controller

• The “access point” for the application

©All rights reserved. Zend Technologies, Inc.

Action Controllers

• Extends Zend_Controller_Action

• Access $_GET, $_POST via request object

• Pass output/headers to response object

©All rights reserved. Zend Technologies, Inc.

Accessing an action controller

©All rights reserved. Zend Technologies, Inc.

Controller Plugins

• Allows you to execute functionality at some point along the execution chain

• Plugins are typically not interactive like helpers

• Need to extend Zend_Controller_Plugin_Abstract

©All rights reserved. Zend Technologies, Inc.

Controller Plugins – Hooks

dispatchLoopShutdown()

postDispatch(Zend_Controller_Request_Abstract $request)

preDispatch(Zend_Controller_Request_Abstract $request)

dispatchLoopStartup(Zend_Controller_Request_Abstract $request)

routeShutdown(Zend_Controller_Request_Abstract $request)

routeStartup(Zend_Controller_Request_Abstract $request)

©All rights reserved. Zend Technologies, Inc.

Controller Plugin - Example

class Esc_Application_Plugin_Maintenanceextends Zend_Controller_Plugin_Abstract

{ public function routeShutdown(Zend_Controller_Request_Abstract

$request) { $request->setActionName('index'); $request->setModuleName('default'); $request->setControllerName('maintenance'); } }

©All rights reserved. Zend Technologies, Inc.

Controller Helpers

• Inject on-demand functionality into action controllers Cache

Context Switching (“Do I use HTML, JSON, XML?”)

View Renderer

Build your own

• Minimize the need to extend Zend_Controller_Action

• Has init(), preDispatch(), postDispatch() hooks Only called if a helper object has been instantiated

©All rights reserved. Zend Technologies, Inc.

Controller Helpers – Building your own

• Must extend Zend_Controller_Action_Helper_Abstract

• Must 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'

);

©All rights reserved. Zend Technologies, Inc.

Zend_View

• Used to handle the view (user interface) from BL

• Older style apps have the two mixed

• Can be used separately from MVC (if you like) Useful if you want to re-use view helpers or form

components

• If using MVC, generally stored in controllers/../views/script

©All rights reserved. Zend Technologies, Inc.

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');

©All rights reserved. Zend Technologies, Inc.

Zend_View – Step 2: Rendering data

<?php if ($this->books): ?> <table> <tr> <th>Author</th> <th>Title</th> </tr> <?php foreach ($this->books as $key => $val): ?> <tr> <td><?php echo $this->escape($val['author']) ?></td> <td><?php echo $this->escape($val['title']) ?></td> </tr> <?php endforeach; ?> </table><?php else: ?><p>There are no books to display.</p><?php endif;?>

©All rights reserved. Zend Technologies, Inc.

Using the ViewRenderer

• An action helper that is loaded by default

• Executes in the postDispatch() hook

• Examines the controller/action combination and automatically runs the proper view script

IndexController::indexAction()/views/scripts/index/index.phtml

©All rights reserved. Zend Technologies, Inc.

View Helpers

• View helpers make your life easier

• Used to provide additional functionality similar to an action helper, but for the view

• Referenced via the $this object when in a view

• Loaded using a plugin loader

• Used to keep logic out of the view (very important) Try to limit views to if and foreach statements

©All rights reserved. Zend Technologies, Inc.

View Helpers Examples

• Easy translation integration

echo $this->translate('Hello World');

• Capturing JS so it can be output elsewhere

<?php $this->headScript()->captureStart(); ?>

alert('Hello World');

<?php $this->headScript()->captureEnd(); ?>

©All rights reserved. Zend Technologies, Inc.

View Helpers

• You can build your own!

• Does not need to implement any interface or abstract class

• Generally placed in /views/helpers (configurable)

• Must have a method name defined as the same name of the class My_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);

}}

©All rights reserved. Zend Technologies, Inc.

Using Partials

• Partials are used to render small, re-usable portions of the view

• Handled via a view helper Partial

PartialLoop• Very useful for any iterative functionality

• Arrays

• Zend_Db_Table_Rowset

• Anything implementing the Iterator interface

©All rights reserved. Zend Technologies, Inc.

The Model

• Unlike other frameworks it is any class that represents your data or business logic

• Could be a service object

• Could be a text file

• Could be an LDAP entry

• Could be a Zend_Db object

©All rights reserved. Zend Technologies, Inc.

Zend_Db

• Database abstraction layer (as opposed to access abstraction layer)

• Several different database vendors are supported

• Abstractions for common functionality such as select, insert, update, delete, limit, offset or transactions

• Connects to the database on demand

• Adapter instance is usually created via Zend_Db::factory()

• Integrated database profiling

©All rights reserved. Zend Technologies, Inc.

Zend_Db_Select

• Provides a vendor-independent mechanism for creating select statements

• Very 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.

©All rights reserved. Zend Technologies, Inc.

ORM

• Uses the Table/Row Data Gateway Design Patterns

• One class to represent the table

• One class to represent a row in the table

©All rights reserved. Zend Technologies, Inc.

ORM – The Table

• Table classes extend Zend_Db_Table_Abstract

• Handles 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' ), );}

©All rights reserved. Zend Technologies, Inc.

ORM – The Row

• Model classes extend Zend_Db_Table_Row_Abstract

class Model_City extends Zend_Db_Table_Row_Abstract{}• Row data is accessed via a __get call

• Good idea to use getters and setters to access them (great for code completion)

©All rights reserved. Zend Technologies, Inc.

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();

©All rights reserved. Zend Technologies, Inc.

ORM - Relationships

• Retrieve an instance of the row class

• Call 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' ), );}

©All rights reserved. Zend Technologies, Inc.

Calling a related object

$tabs = $comment ->findModel_DbTable_TagViaModel_DbTable_TagContent();

• Write a getter that defines that in your model

class Model_Content extends Esc_ModelAbstract{ public function getTags() { return $this ->findModel_DbTable_TagViaModel_DbTable_TagContent() }}

© 2009 All rights reserved. Zend Technologies, Inc.

UNIT TESTING MVC

©All rights reserved. Zend Technologies, Inc.

Unit Testing

• Why Unit Test? Simplify maintenance

It defines expectations

It describes behaviors identified by the application

It tells us when new changes break existing code and behaviors

©All rights reserved. Zend Technologies, Inc.

Terms

• Unit The piece of code you are testing

• Test A piece of code that calls the piece of code you’re testing

• Assertion Validating return types or results of the test

• Code Coverage A report on which lines of code have been tested

• Used to determine additional tests that need to be written

• Continuous Integration The continuous application of quality control, i.e. unit tests

©All rights reserved. Zend Technologies, Inc.

Testing the model

• The easiest of all

• Test classes typically extend PHPUnit_Framework_TestCase

©All rights reserved. Zend Technologies, Inc.

Testing the controller

• Setting up the test Test class extends Zend_Test_PHPUnit_ControllerTestCase

If testing Zend_Application make sure you add the bootstrap in the setUp() method

Make sure you reset() your tests• Response

• Request

• Layout

• Helper Broker

©All rights reserved. Zend Technologies, Inc.

Testing the controller

• You can test Routing (also good for checking authorization)

Response codes

Output (we’ll look at that next)

©All rights reserved. Zend Technologies, Inc.

Testing the view

• Best tested through the controller

• Define which HTML elements need to be present on the page and verify that they exist or have certain values

• Can be done using CSS Selectors

Xpath Queries

©All rights reserved. Zend Technologies, Inc.

Zend_Layout

• Implements Two Step View pattern

• Same name as a dance in Texas, but that’s not important

© 2009 All rights reserved. Zend Technologies, Inc.

A LITTLE MORE ADVANCED…

©All rights reserved. Zend Technologies, Inc.

Zend_Application

• Used for defining an application context

• Zend_Controller_Front just handled the brokering of the request

• Zend_Application handles Bootstrapping (dev/testing/staging/production)

Creating the autoloader

Dispatching

Resource creation

©All rights reserved. Zend Technologies, Inc.

Bootstrapping

• Implements Zend_Application_Bootstrap_Bootstrapper Used to bootstrap (set up the environment) and then

execute the request

Most applications can simply extend Zend_Application_Bootstrap_Bootstrap• This is what we will assume you are using

©All rights reserved. Zend Technologies, Inc.

Bootstrapping

• Resource methods

• Use the resource autoloader Zend_Application_Module_Autoloader placed in

_initAutoload()

• Order

1. Zend_Application::bootstrap()

2. Bootstrap class instantiated

3. Any methods starting with _init() are called and the return value is placed in a container

4. Action retrieves the resource through calling getInvokeArg() and naming the resource

©All rights reserved. Zend Technologies, Inc.

Bootstrapping

• Bootstrap 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 needed Best practice? Don’t know. Kevin’s practice? Yes.

Therefore it is good

©All rights reserved. Zend Technologies, Inc.

Resources

• Pluggable pieces of functionality tied to the application

• Ties functionality directly in with the configuration

• Sample of existing plugins Cachemanager

Db

Log

Frontcontroller

Translate

© 2009 All rights reserved. Zend Technologies, Inc.

SERVICES

©All rights reserved. Zend Technologies, Inc.

Service Theory

• Many services have a very similar execution flow

1. Receive request

2. Find class that can service the request

3. Instantiate object that can handle the request

4. Return result to client

Why re-invent the wheel?

©All rights reserved. Zend Technologies, Inc.

Zend_Server

• Base component for several service-oriented components

• Primarily used for reflection and a standard interface Actual implementation is left to component

©All rights reserved. Zend Technologies, Inc.

Zend_*_Server

• Several components implement Zend_Server_Abstract

• Useful for standardized web service implementation

foreach (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();

©All rights reserved. Zend Technologies, Inc.112

Writing Re-usable Models

• Write your application logic once, but use it in many different ways

• Why? MVC is only one consumer

Can 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)

©All rights reserved. Zend Technologies, Inc.

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 dependencies

©All rights reserved. Zend Technologies, Inc.

Data Access Objects

Data Mappers

Domain Mappers

Service Layer

Service Layer in Perspective

©All rights reserved. Zend Technologies, Inc.

Benefits to Service Layers

Allows easy consumption of the application via your MVC layer

Allows easy re-use of your application via services

Write CLI scripts that consume the Service Layer

©All rights reserved. Zend Technologies, Inc.

What kind of application logic?

Validation and filtering Authentication and Authorization Transactions and interactions between model

entities

©All rights reserved. Zend Technologies, Inc.117

class PersonService{ public function create(array $data) { $person = new Person(); if (!$data = $this->getValidator() ->isValid($data) ) { throw new InvalidArgumentException(); } $person->username = $data['username']; $person->password = $data['password']; $person->email = $data['email']; $this->getMapper()->save($person); return $person; }}

class PersonService{ public function create(array $data) { $person = new Person(); if (!$data = $this->getValidator() ->isValid($data) ) { throw new InvalidArgumentException(); } $person->username = $data['username']; $person->password = $data['password']; $person->email = $data['email']; $this->getMapper()->save($person); return $person; }}

©All rights reserved. Zend Technologies, Inc.

Return objects implementing __toString() and/or toArray()

Easily converted to a variety of formats for your XHR clients

JSON, XML

Easy to cache Strings and arrays serialize and deserialize easily

©All rights reserved. Zend Technologies, Inc.

Returning data

class Foo{ public function __toString() { return 'foo'; }

public function toArray() { $array = array(); foreach ($this->_nodes as $node) { $array[] = $node->name; } return $array; }}

119

©All rights reserved. Zend Technologies, Inc.

Zend_Json

• Useful for encoding/decoding data

$data = range(1, 20);echo Zend_Json::encode($data);• meh

• Zend_Json_Server is neato

• JSON-RPC implementation

• Supported by Dojo

Jquery (via plugin)

Several more

©All rights reserved. Zend Technologies, Inc.

Zend_Json

• Server 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*/});

});

©All rights reserved. Zend Technologies, Inc.

Zend_Amf

• AMF = Action Message Format

• Proprietary, Open Spec protocol developed by Adobe

• Used primarily for implementing a service that communicates with Flash applications

• Zend_Amf_Server extends Zend_Server_Abstract Works well with switching between JSON, XML-RPC

AMF supports typed parameters and return values

• Setting up an AMF interface in Flash Builder/Zend Studio

©All rights reserved. Zend Technologies, Inc.

Zend_Service_Twitter

• Stupid easy Twitter access

$twitter = new Zend_Service_Twitter('mytwitterusername','password‘

);

$response = $twitter->status->update('OSI Days Rocks!‘

);

©All rights reserved. Zend Technologies, Inc.

Zend_Service_Twitter

• Public 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'];}

© 2009 All rights reserved. Zend Technologies, Inc.

ZEND FRAMEWORK 2.0

©All rights reserved. Zend Technologies, Inc.

What will ZF 2 be like?

• Goals Ease the learning curve

Make extending the framework trivially simple

Improve baseline performance of the framework

Simplify maintenance of the framework

Be an exemplar of PHP 5.3 usage

Provide mechanisms for using just the parts of the framework needed

©All rights reserved. Zend Technologies, Inc.

What will ZF 2 be like?

• Roadmap Standardized Option Keys

Exceptions. Each component will have it's own Exception interface

Design By Contract

Elimination of most singletons

Create general-purpose, cross-functional components to reduce duplicate code

Usage of new language features within plugin architectures, specifically __invoke() and closures

©All rights reserved. Zend Technologies, Inc.

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)

©All rights reserved. Zend Technologies, Inc.

What will ZF 2 be like?

• Should you be thinking about ZF2?

• Not yet

© 2009 All rights reserved. Zend Technologies, Inc.

THANK YOU!

©All rights reserved. Zend Technologies, Inc.

Follow us!

Zend Technologies

http://twitter.com/zend

http://twitter.com/kpschrade (me!)

©All rights reserved. Zend Technologies, Inc.

Get this information and all the examples at eschrade.com…

©All rights reserved. Zend Technologies, Inc.

Remember… 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.0