Getting Started with Zend Framework Matthew Weier O'Phinney Software Architect Zend Framework
Just Another  PHP Hacker Who's this guy?
Matthew Weier O'Phinney Contributor to Zend Framework since pre-0.1.0; used ZF internally at Zend. Component lead on MVC since August 2006. Full-time Zend Framework developer since December 2007. Software Architect since April 2008.
What we'll cover Bird's-eye view of Zend Framework How to start integrating Zend Framework in your applications MVC overview Quick Start to developing applications using Zend Framework's MVC
What is Zend Framework? It's just another PHP framework
No, what is Zend Framework? It's a glue library.
No, really, what is Zend Framework? PHP 5 library for web development productivity Open source New BSD license is business-friendly Free for development and distribution CLA process assures that the code is free of legal issues Class library – fully OOP Documentation – in many languages Quality & testing – fully unit tested >80% code coverage required; >90% encouraged
Zend Framework Philosophy Simplicity and Extensibility Easy solutions for the 80% most commonly-used functionality for web applications Extensibility enables easy customization, to solve the remaining 20% No complex XML configuration files Good object-oriented and agile practices Use-at-will architecture, but also: Full stack framework Designed for extensibility Frequent testing Frequent interaction with user community
Zend Framework quality process Say what you’re going to do Proposal process Do it Write object oriented components Unit test your component We encourage test-driven development (TDD)‏ Document how it works Verify it matches what you said Open-source development and community review Frequent and thorough testing with PHPUnit Code coverage reports with PHPUnit Review by internal Zend team for compliance
What's in Zend Framework?
How to get started
Two approaches Start using individual components in your existing applications Gradual migration path Add new functionality to your application as you need it Replace existing functionality with well-tested components Start using the Zend Framework MVC layer Develop new applications Have ZF intercept new functionality in your site Create well-tested and testable applications in Zend Framework
MVC Overview
Model-View-Controller Model : Business logic and abstraction View : Presentation layer Controller : Decide which Models and Views to utilize, based on request
Front Controller Intercept all requests Map requests to Action Controllers Dispatch requested Action Controller and return response
Benefits of MVC Separate your code into discrete realms of responsibility Business logic Presentation logic Route decisioning Predictable location of code on the server Typically utilizes OOP => easier to test and re-use Easier to maintain long term
Quick Start
Setup the Project Structure First things first: create your directory structure
Get Zend Framework From http://framework.zend.com/download/latest
Get Zend Framework Extract the archive tar xzf ZendFramework-1.6.1.tar.gz Unzip ZendFramework-1.6.1.zip Or use a GUI frontend Copy or symlink the library/Zend directory you extracted into your library directory:
Create a Virtual Host Simplest version:
Create your .htaccess file php.ini directives: date.timezone: many apps rely on this short_open_tags: view scripts are easier to write with this on error_reporting: default error reporting level – E_ALL|E_STRICT for development display_errors: turn on for development
Create your .htaccess file RewriteRules: any request to a file that does not exist should go to our Zend Framework bootstrap:
Create your bootstrap files index.php:  Indicate we need bootstrapping for our application Load our bootstrap file, and handle any errors Dispatch our front controller
index.php
Create your bootstrap files application/bootstrap.php: Setup application constants Web bootstrap related setup include_path Setup autoloading Front controller setup Add a controller directory Set some application parameters
application/bootstrap.php
Create a controller All controllers extend Zend_Controller_Action Naming conventions Controllers end with 'Controller':  IndexController, GuestbookController Action methods end with 'Action': signAction(), displayAction(), listAction()‏ Controllers should be in the application/controllers/ directory, and named after the class, with a “.php” suffix: application/controllers/IndexController.php application/controllers/GuestbookController.php All “conventions” are configurable!
IndexController.php
But... there's no code there... By default, a view is rendered; you don't need to do anything to enable this. The view rendered is <controllername>/<action>.phtml The view script path resolution is configurable!
Create a view script View scripts go in application/views/scripts/ View script resolution looks for a view script in a subdirectory named after the controller Controller name used is same as it appears on the url: “GuestbookController” appears on the URL as “guestbook” “GuestBookController” appears on the URL as “guest-book” Basically, MixedCased becomes dash-separated View script name is the action name as it appears on the url: “signAction()” appears on the URL as “sign” “myAccountAction()” appears on the URL as “my-account” Basically, camelCased becomes dash-separated
index/index.phtml view script
But... that's just HTML! View scripts use PHP as their templating language – PHP  is  a template language! Mix HTML and PHP Use alternate control structure annotations for readability Use short tags (heavily debated) for brevity
Create an ErrorController Application errors are trapped by the front controller by default When exceptions are detected, ErrorController::errorAction() is invoked Separate 404 (Not Found) errors from 500 (Application) errors to return proper response codes to the user Display errors in development, log them in production Alternately, do something else: Perform a search based on the originally requested URL Display a site map
ErrorController.php
Create a view script for the ErrorController We have a controller and action, so we need a view script Appears in error/error.phtml of the view scripts directory
error/error.phtml
But wait, these aren't complete HTML pages! You're right – they are your application views This leads into our next topic: layouts
Layouts – Design Patterns Two Step View Inject application views into a common view to return Usually associated with a Transform View – think XSLT Composite View Inject rendered views into a common view, OR Render additional views from a master view In a nutshell: build the site view, or layout, from lots of little building blocks, or application views
Layouts – Example Use Cases We want our application views to appear in this:
Zend_Layout Steps: Initialize layouts Perform view initialization (set doctype, etc)‏ Create a layout script
Zend_Layout: bootstrap changes
Zend_Layout: layout script
Configuring your Application Zend Framework is configuration-less But your application may need configuration Zend_Config... allows you to write configurations in several formats provides OOP access to your configuration provides configuration inheritance between sections Zend_Registry  allows you to persist objects – including your configuration – for the duration of the request Put stuff in Take stuff out
Sample INI configuration skeleton
Configuration: bootstrap.php changes
What about the M? The Model? Patterns : Table Data Gateway Abstracts SQL access to a single database table and its rows Often used with Row Data Gateway, which abstracts access to a single table row Table Module Abstracts and restricts access to a table Defines entry points to the table Entry methods contain business logic  Domain Model Abstracts entities and their relationships Not necessarily a 1:1 correspondence with tables
Setting up the Database Adapter Zend_Db::factory() will instantiate the requested adapter Pass our configuration to it Negates the need to modify code going from development to testing to production Set the adapter as the default adapter for our Table Data Gateway (Zend_Db_Table)‏
DB Adapter – Configuration and Bootstrap
Table Data Gateway: Zend_Db_Table Abstracts SQL for interacting with a database table Fetch Rowsets or individual Rows Override methods to enforce data integrity In our application Ensure we get a “created” timestamp on each row Prevent updates to existing rows
Model_DbTable_Guestbook
Model: Table Module Identify access methods: Save entries Fetch all entries Fetch individual entry Attach a data source Often a Table Data Gateway In our case, Model_DbTable_Guestbook
Table Module – Retrieve Table Data Gateway
Table Module – Access Methods
Using the Model in the Controller Controller needs to retrieve Model To start, let's fetch listings
Adding the Model to the Controller
Create a Form Zend_Form: Provides input filtering: Filter chains to sanitize data prior to validation Validation chains to ensure the data provided is valid Allows rendering form Follows decorator pattern Completely configurable Output in any format your application needs: HTML, PDF, XML, etc.
Create a form – Identify elements Guestbook form: Email address Comment Captcha to reduce spam entries Submit button
Create a form – Guestbook form
Create a form – Guestbook form (cont.)‏
Using the Form in the Controller Controller needs to fetch form object On landing page, display the form On POST requests, attempt to validate the form On successful submission, redirect
Adding the form to the controller
Demonstration
Summary
What we learned Recommended project structure How to get and install Zend Framework How to configure your Apache vhost How to setup your php.ini settings and RewriteRules What your bootstrap files are and what they should contain How to create Action Controllers and View Scripts How to create and initialize layouts How to use configuration and the registry How to create a model, including database access How to create a form
Where to go from here Zend Framework QuickStart Guide: http://framework.zend.com/docs/quickstart Zend Framework Manual http://framework.zend.com/manual/manual Zend Framework Wiki (proposals, tutorials, etc.) http://framework.zend.com/wiki Zend Developer Zone (tutorials, articles, announcements) http://devzone.zend.com/
Thank you!

Getting Started with Zend Framework

  • 1.
    Getting Started withZend Framework Matthew Weier O'Phinney Software Architect Zend Framework
  • 2.
    Just Another PHP Hacker Who's this guy?
  • 3.
    Matthew Weier O'PhinneyContributor to Zend Framework since pre-0.1.0; used ZF internally at Zend. Component lead on MVC since August 2006. Full-time Zend Framework developer since December 2007. Software Architect since April 2008.
  • 4.
    What we'll coverBird's-eye view of Zend Framework How to start integrating Zend Framework in your applications MVC overview Quick Start to developing applications using Zend Framework's MVC
  • 5.
    What is ZendFramework? It's just another PHP framework
  • 6.
    No, what isZend Framework? It's a glue library.
  • 7.
    No, really, whatis Zend Framework? PHP 5 library for web development productivity Open source New BSD license is business-friendly Free for development and distribution CLA process assures that the code is free of legal issues Class library – fully OOP Documentation – in many languages Quality & testing – fully unit tested >80% code coverage required; >90% encouraged
  • 8.
    Zend Framework PhilosophySimplicity and Extensibility Easy solutions for the 80% most commonly-used functionality for web applications Extensibility enables easy customization, to solve the remaining 20% No complex XML configuration files Good object-oriented and agile practices Use-at-will architecture, but also: Full stack framework Designed for extensibility Frequent testing Frequent interaction with user community
  • 9.
    Zend Framework qualityprocess Say what you’re going to do Proposal process Do it Write object oriented components Unit test your component We encourage test-driven development (TDD)‏ Document how it works Verify it matches what you said Open-source development and community review Frequent and thorough testing with PHPUnit Code coverage reports with PHPUnit Review by internal Zend team for compliance
  • 10.
    What's in ZendFramework?
  • 11.
    How to getstarted
  • 12.
    Two approaches Startusing individual components in your existing applications Gradual migration path Add new functionality to your application as you need it Replace existing functionality with well-tested components Start using the Zend Framework MVC layer Develop new applications Have ZF intercept new functionality in your site Create well-tested and testable applications in Zend Framework
  • 13.
  • 14.
    Model-View-Controller Model :Business logic and abstraction View : Presentation layer Controller : Decide which Models and Views to utilize, based on request
  • 15.
    Front Controller Interceptall requests Map requests to Action Controllers Dispatch requested Action Controller and return response
  • 16.
    Benefits of MVCSeparate your code into discrete realms of responsibility Business logic Presentation logic Route decisioning Predictable location of code on the server Typically utilizes OOP => easier to test and re-use Easier to maintain long term
  • 17.
  • 18.
    Setup the ProjectStructure First things first: create your directory structure
  • 19.
    Get Zend FrameworkFrom http://framework.zend.com/download/latest
  • 20.
    Get Zend FrameworkExtract the archive tar xzf ZendFramework-1.6.1.tar.gz Unzip ZendFramework-1.6.1.zip Or use a GUI frontend Copy or symlink the library/Zend directory you extracted into your library directory:
  • 21.
    Create a VirtualHost Simplest version:
  • 22.
    Create your .htaccessfile php.ini directives: date.timezone: many apps rely on this short_open_tags: view scripts are easier to write with this on error_reporting: default error reporting level – E_ALL|E_STRICT for development display_errors: turn on for development
  • 23.
    Create your .htaccessfile RewriteRules: any request to a file that does not exist should go to our Zend Framework bootstrap:
  • 24.
    Create your bootstrapfiles index.php: Indicate we need bootstrapping for our application Load our bootstrap file, and handle any errors Dispatch our front controller
  • 25.
  • 26.
    Create your bootstrapfiles application/bootstrap.php: Setup application constants Web bootstrap related setup include_path Setup autoloading Front controller setup Add a controller directory Set some application parameters
  • 27.
  • 28.
    Create a controllerAll controllers extend Zend_Controller_Action Naming conventions Controllers end with 'Controller': IndexController, GuestbookController Action methods end with 'Action': signAction(), displayAction(), listAction()‏ Controllers should be in the application/controllers/ directory, and named after the class, with a “.php” suffix: application/controllers/IndexController.php application/controllers/GuestbookController.php All “conventions” are configurable!
  • 29.
  • 30.
    But... there's nocode there... By default, a view is rendered; you don't need to do anything to enable this. The view rendered is <controllername>/<action>.phtml The view script path resolution is configurable!
  • 31.
    Create a viewscript View scripts go in application/views/scripts/ View script resolution looks for a view script in a subdirectory named after the controller Controller name used is same as it appears on the url: “GuestbookController” appears on the URL as “guestbook” “GuestBookController” appears on the URL as “guest-book” Basically, MixedCased becomes dash-separated View script name is the action name as it appears on the url: “signAction()” appears on the URL as “sign” “myAccountAction()” appears on the URL as “my-account” Basically, camelCased becomes dash-separated
  • 32.
  • 33.
    But... that's justHTML! View scripts use PHP as their templating language – PHP is a template language! Mix HTML and PHP Use alternate control structure annotations for readability Use short tags (heavily debated) for brevity
  • 34.
    Create an ErrorControllerApplication errors are trapped by the front controller by default When exceptions are detected, ErrorController::errorAction() is invoked Separate 404 (Not Found) errors from 500 (Application) errors to return proper response codes to the user Display errors in development, log them in production Alternately, do something else: Perform a search based on the originally requested URL Display a site map
  • 35.
  • 36.
    Create a viewscript for the ErrorController We have a controller and action, so we need a view script Appears in error/error.phtml of the view scripts directory
  • 37.
  • 38.
    But wait, thesearen't complete HTML pages! You're right – they are your application views This leads into our next topic: layouts
  • 39.
    Layouts – DesignPatterns Two Step View Inject application views into a common view to return Usually associated with a Transform View – think XSLT Composite View Inject rendered views into a common view, OR Render additional views from a master view In a nutshell: build the site view, or layout, from lots of little building blocks, or application views
  • 40.
    Layouts – ExampleUse Cases We want our application views to appear in this:
  • 41.
    Zend_Layout Steps: Initializelayouts Perform view initialization (set doctype, etc)‏ Create a layout script
  • 42.
  • 43.
  • 44.
    Configuring your ApplicationZend Framework is configuration-less But your application may need configuration Zend_Config... allows you to write configurations in several formats provides OOP access to your configuration provides configuration inheritance between sections Zend_Registry allows you to persist objects – including your configuration – for the duration of the request Put stuff in Take stuff out
  • 45.
  • 46.
  • 47.
    What about theM? The Model? Patterns : Table Data Gateway Abstracts SQL access to a single database table and its rows Often used with Row Data Gateway, which abstracts access to a single table row Table Module Abstracts and restricts access to a table Defines entry points to the table Entry methods contain business logic Domain Model Abstracts entities and their relationships Not necessarily a 1:1 correspondence with tables
  • 48.
    Setting up theDatabase Adapter Zend_Db::factory() will instantiate the requested adapter Pass our configuration to it Negates the need to modify code going from development to testing to production Set the adapter as the default adapter for our Table Data Gateway (Zend_Db_Table)‏
  • 49.
    DB Adapter –Configuration and Bootstrap
  • 50.
    Table Data Gateway:Zend_Db_Table Abstracts SQL for interacting with a database table Fetch Rowsets or individual Rows Override methods to enforce data integrity In our application Ensure we get a “created” timestamp on each row Prevent updates to existing rows
  • 51.
  • 52.
    Model: Table ModuleIdentify access methods: Save entries Fetch all entries Fetch individual entry Attach a data source Often a Table Data Gateway In our case, Model_DbTable_Guestbook
  • 53.
    Table Module –Retrieve Table Data Gateway
  • 54.
    Table Module –Access Methods
  • 55.
    Using the Modelin the Controller Controller needs to retrieve Model To start, let's fetch listings
  • 56.
    Adding the Modelto the Controller
  • 57.
    Create a FormZend_Form: Provides input filtering: Filter chains to sanitize data prior to validation Validation chains to ensure the data provided is valid Allows rendering form Follows decorator pattern Completely configurable Output in any format your application needs: HTML, PDF, XML, etc.
  • 58.
    Create a form– Identify elements Guestbook form: Email address Comment Captcha to reduce spam entries Submit button
  • 59.
    Create a form– Guestbook form
  • 60.
    Create a form– Guestbook form (cont.)‏
  • 61.
    Using the Formin the Controller Controller needs to fetch form object On landing page, display the form On POST requests, attempt to validate the form On successful submission, redirect
  • 62.
    Adding the formto the controller
  • 63.
  • 64.
  • 65.
    What we learnedRecommended project structure How to get and install Zend Framework How to configure your Apache vhost How to setup your php.ini settings and RewriteRules What your bootstrap files are and what they should contain How to create Action Controllers and View Scripts How to create and initialize layouts How to use configuration and the registry How to create a model, including database access How to create a form
  • 66.
    Where to gofrom here Zend Framework QuickStart Guide: http://framework.zend.com/docs/quickstart Zend Framework Manual http://framework.zend.com/manual/manual Zend Framework Wiki (proposals, tutorials, etc.) http://framework.zend.com/wiki Zend Developer Zone (tutorials, articles, announcements) http://devzone.zend.com/
  • 67.