Zend Framework Tutorial, ZendCon 2009

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

3 comments

Comments 1 - 3 of 3 previous next Post a comment

  • + weierophinney Matthew Weier O'Phinney 1 month ago
    @baohx2000 - yes, I will be posting on my blog soon, and will also link to the archive here when I have.
  • + baohx2000 baohx2000 1 month ago
    Will you be posting code for the 'Step X' slides?
    Great presentation (at least the slides since I couldn’t go this year)
  • + weierophinney Matthew Weier O'Phinney 1 month ago
    Just a note: when you hit the slides that are marked 'Step X' -- you’ve hit about the 1 hour mark of a 3 hour tutorial. The remainder of the slides are placeholders, and simply indicate the next step in a hands-on demonstration where we built a pastebin application.
Post a comment
Embed Video
Edit your comment Cancel

11 Favorites

Zend Framework Tutorial, ZendCon 2009 - Presentation Transcript

  1. Zend Framework Tutorial Matthew Weier O'Phinney Project Lead Zend Framework ZendCon 2009 19 October 2009
  2. About me:
    • ZF Contributor since January 2006
    • Assigned to the ZF team in July 2007
    • Promoted to Software Architect in April 2008
    • Project Lead since April 2009
    Photo © 2009, Chris Shiflett
  3. What we'll cover
    • What is Zend Framework?
    • Getting and Installing Zend Framework
    • Utilities and Patterns used throughout ZF
    • Using ZF's MVC layer: Hands-on demonstration: Pastebin
  4. What is Zend Framework?
  5. Full Stack Framework?
  6. Component Library?
  7. Both.
  8.  
  9. Getting and Installing Zend Framework
  10. Always found at: http://framework.zend.com /download/latest
  11. Zend Server
  12. CDN Links
  13. Direct Links
    • Use CLI: % tar xzf ZendFramework-1.9.2-minimal.tar.gz % unzip ZendFramework-1.9.2-minimal.zip
    • Or use a GUI file manager
    Unzip/Untar
  14. Add to your include_path ; UNIX: "/path1:/path2" include_path = ".:/home/matthew/zf/library"
  15. Add to your include_path # Goes in either a <VirtualHost>, # <Directory> or .htaccess: php_value include_path &quot;.:/home/matthew/zf/library&quot;
  16. Add to your include_path <?php set_include_path( implode (PATH_SEPARATOR, array ( '.' , '/home/matthew/zf/library' , get_include_path(), )));
  17. Utilities and Patterns Used throughout Zend Framework
  18. The Autoloader
    • Class names have a 1:1 relationship with the FileSystem: Zend_Db => Zend/Db.php
    • The initial class prefix is called the “vendor” or “namespace” prefix: “Zend_”, “ZendX_”
    • Register either namespace prefixes or actual autoloader callbacks with the ZF autoloader
    Rules
  19. Initialize the autoloader require_once 'Zend/Loader/Autoloader.php' ; Zend_Loader_Autoloader::getInstance();
  20. Register namespaces $al = Zend_Loader_Autoloader::getInstance(); $al ->registerNamespace( 'Foo_' ); $al ->registerNamespace( array ( 'Foo_' , 'Bar_' ));
  21. Register other autoloaders $al = Zend_Loader_Autoloader::getInstance(); $al ->registerNamespace( 'Doctrine' ); $al ->pushAutoloader( array ( 'Doctrine' , 'autoload' ), 'Doctrine_' );
    • Groups of resources with a common vendor prefix/namespace
    • No 1:1 mapping between class name and filename
    • Define arbitrary mappings, or use Zend_Application_Module_Autoloader for use with MVC modules
    Resource Autoloaders
  22. Create a resource autoloader // Initialize resource autoloader: $loader = new Zend_Loader_Autoloader_Resource( array ( 'namespace' => 'Foo' , 'basePath' => $path , )); // Map $path/forms/*.php to Foo_Form_*: $loader ->addResourceType( 'form' , 'forms' , 'Form' );
  23. Create a module autoloader /* * Maps: * - forms/ -> Foo_Form_* * - models/ -> Foo_Model_* * - models/DbTable -> Foo_Model_DbTable_* * - plugins -> Foo_Plugin_* * - services -> Foo_Service_* * - views/helpers -> Foo_View_Helper_* * - views/filters -> Foo_View_Filter_* */ $loader = new Zend_Application_Module_Autoloader( array ( 'namespace' => 'Foo' , 'basePath' => dirname (__FILE__), ));
  24. Plugins
    • For those times when 1:1 doesn't work (e.g., application code)
    • Standard pattern: “all code in this location shares the same class prefix” (aka PrefixPath)
    • Plugin loader is passed a “short name,” and attempts to resolve it to a known PrefixPath
    Rules
  25. Example $element ->addPrefixPath( 'Foo_Validate' , // PREFIX 'foo/plugins/validators/' , // PATH 'validate' ); foo/ |-- plugins/ | |-- validators/ | | |-- Even.php | | |-- Dozens.php | | |-- Int.php
  26. Invoking plugins $element ->addValidator( 'NotEmpty' ) ->addValidator( 'Int' ) ->addValidator( 'Even' ) ->addValidator( 'Dozens' ); New, custom validators Custom validator overriding existing validator
  27. Zend_Config
    • Zend Framework is configurationless, but often your applications are not
    • Many common configuration formats: XML, INI, PHP
    • Access to configuration values should not vary between backends
    • Configuration inheritance is useful
    Why Zend_Config?
  28. Sample INI config [production] app.name = &quot;Foo!&quot; db.adapter = &quot;Pdo_Mysql&quot; db.params.username = &quot;foo&quot; db.params.password = &quot;bar&quot; db.params.dbname = &quot;foodb&quot; db.params.host = &quot;127.0.0.1&quot; [testing : production] db.adapter = &quot;Pdo_Sqlite&quot; db.params.dbname = APPLICATION_PATH &quot;/data/test.db&quot;
  29. Sample XML config <?xml version = &quot;1.0&quot; ?> <config> <production> <app><name> Foo! </name></app> <db> <adapter> Pdo_Mysql </adapter> <params username = &quot;foo&quot; password = &quot;bar&quot; dbname = &quot;foodb&quot; host = &quot;127.0.0.1&quot; /> </db> </production> <testing extends = &quot;production&quot; > <db> <adapter> Pdo_Sqlite </adapter> <params dbname = &quot;/data/test.db&quot; /> </db> </testing> </config>
  30. Sample PHP config $production = include 'production.conf.php' ; $config = array ( 'db' => array ( 'adapter' => 'Pdo_Sqlite' , 'params' => array ( 'dbname' => APP_PATH . '/../data/test.db' , ), ) ); $config = $production + $config ; return $config ;
  31. Instantiating a Config object // Load 'testing' section of INI configuration: $config = new Zend_Config_Ini( $fileName , 'testing' ); // Load 'testing' section of XML configuration: $config = new Zend_Config_Xml( $fileName , 'testing' ); // Load 'testing' configuration via PHP array: $config = include 'testing.conf.php' ; $config = new Zend_Config( $config );
  32. Using Config objects // Multiple levels: $appName = $config ->app->name; // Using config object as argument $db = Zend_Db::factory( $config ->db);
  33. Using Zend Framework's MVC Layer
    • Learn how to create a new ZF MVC project
    • Learn how to use various MVC components:
      • Zend_Application, Zend_Controller_Front, Zend_Controller_Action, Zend_Controller_Router, Zend_Db_Table, Zend_View, Action Helpers, View Helpers, Zend_Form, Zend_Layout, etc.
    • Learn concepts related to separation of concerns
    Goals
    • Create “pastes” with optional expiry; allow listing pastes by username
    • Single table is ideal for demonstrating simple component interactions
    • Ask questions as you have them!
    The Application: Pastebin
    • A Paste consists of:
    Pastebin Specification code content (required) summary (optional) code_type content type (required, default to plain text) username (optional) timestamp (required; created on commit) expiry (optional) identifier (required; a unique hash)
    • Each paste will have a unique URL
    • Pastes may optionally expire, in which case they won't be displayed
    • Pastes may be listed by username
    Pastebin Specification
  34. Step 1: Create the project
    • In bin/zf.sh or bin/zf.bat of your ZF install (choose based on your OS)
    • Place bin/ in your path, or create an alias on your path: alias zf=/path/to/bin/zf.sh
    • Or use pear.zfcampus.org PEAR channel
    Locate the zf utility
  35. Create the project # Unix: % zf.sh create project quickstart # DOS/Windows: C:> zf.bat create project quickstart
  36. Add ZF to the project # Symlink: % cd library; ln -s path/to/ZendFramework/library/Zend . # Copy: % cd library; cp -r path/to/ZendFramework/library/Zend .
  37. Create a vhost <VirtualHost *: 80 > ServerAdmin you@atyour.tld DocumentRoot /abs/path/to/quickstart/public ServerName quickstart <Directory /abs/path/to/quickstart/public > DirectoryIndex index.php AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost>
  38. Add a hosts entry 127.0.0.1 quickstart
  39. Fire up your browser!
  40. Looking under the hood
  41. The directory tree quickstart |-- application | |-- Bootstrap.php | |-- configs | | `-- application.ini | |-- controllers | | |-- ErrorController.php | | ` -- IndexController.php | |-- models | `-- views | |-- helpers | ` -- scripts | |-- error | | `-- error.phtml | ` -- index | `-- index.phtml |-- library |-- public | ` -- index.php `-- tests |-- application | ` -- bootstrap.php |-- library | `-- bootstrap.php ` -- phpunit.xml 14 directories, 10 files
  42. The bootstrap <?php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { }
  43. Configuration [production] phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0 includePaths.library = APPLICATION_PATH &quot;/../library&quot; bootstrap.path = APPLICATION_PATH &quot;/Bootstrap.php&quot; bootstrap.class = &quot;Bootstrap&quot; resources.frontController.controllerDirectory = APPLICATION_PATH &quot;/controllers&quot; [staging : production] [testing : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1 [development : production] phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1
  44. Index (default) controller <?php class IndexController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ } public function indexAction() { // action body } }
  45. Error controller class ErrorController extends Zend_Controller_Action { public function errorAction() { $errors = $this ->_getParam( 'error_handler' ); switch ( $errors ->type) { case 'EXCEPTION_NO_CONTROLLER': case 'EXCEPTION_NO_ACTION': // 404 error -- controller or action not found $this ->getResponse()->setHttpResponseCode( 404 ); $this ->view->message = 'Page not found' ; break ; default: // application error $this ->getResponse()->setHttpResponseCode( 500 ); $this ->view->message = 'Application error' ; break ; } $this ->view->exception = $errors ->exception; $this ->view->request = $errors ->request; } }
  46. Index view (home page) <div id = &quot;welcome&quot; > <h1> Welcome to the <span id = &quot;zf-name&quot; > Zend Framework! </span> </h1> <h3> This is your project's main page </h3> <!-- and a little bit more markup --> </div>
  47. Error view <h1>An error occurred</h1> <h2><?php echo $this ->message ?></h2> <?php if ( 'development' == APPLICATION_ENV): ?> <h3>Exception information:</h3> <p> <b>Message:</b> <?php echo $this ->exception->getMessage() ?> </p> <h3>Stack trace:</h3> <pre> <?php echo $this ->exception->getTraceAsString() ?> </pre> <h3>Request Parameters:</h3> <pre> <?php var_dump ( $this ->request->getParams()) ?> </pre> <?php endif ?>
  48. .htaccess file SetEnv APPLICATION_ENV development RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L]
  49. index.php (environment) <?php // Define path to application directory defined ( 'APPLICATION_PATH' ) || define ( 'APPLICATION_PATH' , realpath ( dirname (__FILE__) . '/../application' )); // Define application environment defined ( 'APPLICATION_ENV' ) || define ( 'APPLICATION_ENV' , ( getenv ( 'APPLICATION_ENV' ) ? getenv ( 'APPLICATION_ENV' ) : 'production' )); // Ensure library/ is on include_path set_include_path( implode (PATH_SEPARATOR, array ( realpath (APPLICATION_PATH . '/../library' ), get_include_path(), )));
  50. index.php (application) /** Zend_Application */ require_once 'Zend/Application.php' ; // Create application, bootstrap, and run $application = new Zend_Application( APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini' ); $application ->bootstrap() ->run();
  51. Step 2: Create the model
  52. Step 3: Create a form
  53. Step 4: Create a controller
  54. Step 5: Create new routes
  55. Step 6: Create controller actions
  56. Step 7: Create views
  57. Step 8: Create a layout
  58. Step 9: Update the default view
  59. Step 10: Check it out!
  60. Further Steps
    • Add Dojo handling for code highlighting
    • Add CSS for forms
    • Add CSS for errors
    • Add some layout specific styling and/or use dojo containers to improve layout
    • Add Navigation elements to provide a menu/breadcrumbs
    • Add caching (pastes may not be updated; cache forever)
    Make it prettier
  61. Summary or, “The fat guy sings”
    • What Zend Framework is
    • Some common utilities/patterns used (autoloading, plugins, configuration)
    • How to build a ZF MVC application
    We looked at:
  62. Questions? or, “Your turn!”
  63. Thank you. http://framework.zend.com/ http://twitter.com/weierophinney http://slideshare.net/weierophinney Feedback? http://joind.in/talk/view/878

+ Matthew Weier O'PhinneyMatthew Weier O'Phinney, 1 month ago

custom

2023 views, 11 favs, 0 embeds more stats

More info about this document

© All Rights Reserved

Go to text version

  • Total Views 2023
    • 2023 on SlideShare
    • 0 from embeds
  • Comments 3
  • Favorites 11
  • Downloads 156
Most viewed embeds

more

All embeds

less

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

Cancel
File a copyright complaint
Having problems? Go to our helpdesk?

Categories