Beginning Zend Framework Or: How I learned to stop worrying and love the framework. Part 1: Setting up
Preparing Zend Framework <ul><li>Download ZF1.9 </li><ul><li>svn co  http://framework.zend.com/svn/framework/standard/tags...
Alternately, check out the framework into your pear directory. </li></ul>
Preparing ZF Contd. <ul><li>Check out bin (Zend Tool) </li><ul><li>svn co  http://framework.zend.com/svn/framework/standar...
Rename zf.sh to zf and make it executable </li></ul>
Using Zend_Tool to set up your project <ul><li>Create a directory to house your projects </li><ul><li>mkdir projects </li>...
Add project to apache <ul><li>This can vary widely with OS and version, so you're mostly on your own.
Make the DocumentRoot the “public” directory within your  {projectname}  directory.
After reloading apache, you should be able to go to the site you just set up and see the default zend framework page! </li...
Normal Application Setup <ul><li>Normally we would have the domain set up to point directly to the “public” directory </li...
NO php should go in public folder unless it’s simple and framework is overkill for it </li><ul><li>Except for index.php </...
Directory Structure <ul><li>/application </li><ul><li>application files…more in a moment </li></ul><li>/library </li><ul><...
Extra classes/libraries used by the app </li></ul><li>/public </li><ul><li>index.php, html/js/images/etc, anything that sh...
Application Directory <ul><li>Bootstrap.php </li><ul><li>Specific application – framework setup </li></ul><li>configs </li...
Wrong, not classes, simple php+html files. </li></ul></ul>
index.php <ul><li>Prepares include path
Specifies application configuration
Load & run bootstrap </li></ul>
Create a database/table <ul><li>Use whatever tools you're used to </li></ul>CREATE TABLE `user` ( `user_id` INT NOT NULL A...
Add database to app config <ul><li>Edit application/configs/application.ini </li></ul># Database resources.db.adapter = &q...
application.ini <ul><li>Note that application.ini has multiple sections </li><ul><li>Production, Staging, Development
Defined in .htaccess
Can be used to specify different databases for different environments </li></ul></ul>
Configuring the layout <ul><li>What's a layout? </li><ul><li>2-step way of providing “overall” layout to your app
View result html will be placed as “content” in layout
Layout can house dynamic links for header js, css, etc
Easily reached from controller or view. </li></ul></ul>
Layout Contd. <ul><li>Create directory application/layouts and application/layouts/scripts
Add the following to your application.ini: </li></ul>#layout resources.layout.layout = &quot;layout&quot; resources.layout...
Module Layouts <ul><li>We're making an admin module
Let's load a specific admin layout for it </li></ul>
<ul>class Plugin_ModuleLayout extends Zend_Controller_Plugin_Abstract  </ul>{ public function preDispatch(Zend_Controller_...
Enable the plugin <ul><li>Edit application/Bootstrap.php </li></ul>public function _initLayouts() { Zend_Layout::startMvc(...
Application general layout <ul><li>applications/layouts/scripts/layout.phtml </li></ul><?php echo $this->doctype() ?> <htm...
Create a User model <ul><li>application/models/DbTable/User.php </li></ul><?php class Model_DbTable_User extends Zend_Db_T...
User Model Cont'd public function addUser($username, $email, $password, $user_type=1) { // generate unique id for the pass...
User Model... $data = array( 'username' => $username, 'email' => $email, 'password' => $hashed_pwd, 'salt' => $salt, 'user...
User Model... function updateUser($id, $email, $password=null, $user_type=1) { $where = array('user_id = ?' => (int)$id); ...
Autoloader <ul><li>Allow us to call our model class without having to include it manually </li><ul><li>In application/Boot...
Database Profiling in Firebug! <ul><li>Still in Bootstrap.php </li></ul>public function _initDbprofile() { if($this->getEn...
URL Structure <ul><li>Defaults to Index controller & Index action </li><ul><li>/public/{controller}/{action}
Upcoming SlideShare
Loading in...5
×

Zend Framework 1.9 Setup & Using Zend_Tool

10,407

Published on

Presentation for azPHP on setting up a new project using Zend_Tool. Also goes over creating basic modules, controllers, actions, models and layouts.

All code in the presentation has not necessarily been tested. Will update presentation when done.

Published in: Technology, Education
5 Comments
7 Likes
Statistics
Notes
No Downloads
Views
Total Views
10,407
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
259
Comments
5
Likes
7
Embeds 0
No embeds

No notes for slide

Zend Framework 1.9 Setup & Using Zend_Tool

  1. 1. Beginning Zend Framework Or: How I learned to stop worrying and love the framework. Part 1: Setting up
  2. 2. Preparing Zend Framework <ul><li>Download ZF1.9 </li><ul><li>svn co http://framework.zend.com/svn/framework/standard/tags/release-1.9.1/library/Zend </li></ul><li>Add directory containing Zend to php.ini as part of the path.
  3. 3. Alternately, check out the framework into your pear directory. </li></ul>
  4. 4. Preparing ZF Contd. <ul><li>Check out bin (Zend Tool) </li><ul><li>svn co http://framework.zend.com/svn/framework/standard/tags/release-1.9.1/bin </li></ul><li>Copy zf.php and zf.sh to a directory in your path (/usr/bin)
  5. 5. Rename zf.sh to zf and make it executable </li></ul>
  6. 6. Using Zend_Tool to set up your project <ul><li>Create a directory to house your projects </li><ul><li>mkdir projects </li></ul><li>Enter directory </li><ul><li>cd projects </li></ul><li>Create a project using the zf script </li><ul><li>zf create project {projectname} </li></ul></ul>
  7. 7. Add project to apache <ul><li>This can vary widely with OS and version, so you're mostly on your own.
  8. 8. Make the DocumentRoot the “public” directory within your {projectname} directory.
  9. 9. After reloading apache, you should be able to go to the site you just set up and see the default zend framework page! </li></ul>
  10. 10. Normal Application Setup <ul><li>Normally we would have the domain set up to point directly to the “public” directory </li><ul><li>Keeps php code from being directly accessible
  11. 11. NO php should go in public folder unless it’s simple and framework is overkill for it </li><ul><li>Except for index.php </li></ul></ul></ul>
  12. 12. Directory Structure <ul><li>/application </li><ul><li>application files…more in a moment </li></ul><li>/library </li><ul><li>framework files ( /library/Zend )
  13. 13. Extra classes/libraries used by the app </li></ul><li>/public </li><ul><li>index.php, html/js/images/etc, anything that should be directly accessible by the browser </li></ul><li>/tests </li><ul><li>unit tests… another time maybe </li></ul></ul>
  14. 14. Application Directory <ul><li>Bootstrap.php </li><ul><li>Specific application – framework setup </li></ul><li>configs </li><ul><li>Application .ini file (soon) </li></ul><li>controllers </li><ul><li>Holds controller classes (gasp!) </li></ul><li>models </li><ul><li>Holds model classes (double-gasp!) </li></ul><li>views </li><ul><li>You get one guess what goes in here…
  15. 15. Wrong, not classes, simple php+html files. </li></ul></ul>
  16. 16. index.php <ul><li>Prepares include path
  17. 17. Specifies application configuration
  18. 18. Load & run bootstrap </li></ul>
  19. 19. Create a database/table <ul><li>Use whatever tools you're used to </li></ul>CREATE TABLE `user` ( `user_id` INT NOT NULL AUTO_INCREMENT , `username` VARCHAR( 255 ) NOT NULL , `email` VARCHAR( 128 ) NOT NULL , `password` VARCHAR( 32 ) NOT NULL , `salt` VARCHAR( 32 ) NOT NULL , `api_key` VARCHAR( 32 ) NOT NULL , `api_secret` VARCHAR( 32 ) NOT NULL , `user_type` TINYINT NOT NULL , PRIMARY KEY ( `user_id` ), UNIQUE KEY `username` (`username`) )
  20. 20. Add database to app config <ul><li>Edit application/configs/application.ini </li></ul># Database resources.db.adapter = &quot;pdo_mysql&quot; resources.db.params.host = &quot;localhost&quot; resources.db.params.username = &quot;zfclass&quot; resources.db.params.password = &quot;zfclass&quot; resources.db.params.dbname = &quot;zfclass_ {yourname} &quot; resources.db.isDefaultTableAdapter = true
  21. 21. application.ini <ul><li>Note that application.ini has multiple sections </li><ul><li>Production, Staging, Development
  22. 22. Defined in .htaccess
  23. 23. Can be used to specify different databases for different environments </li></ul></ul>
  24. 24. Configuring the layout <ul><li>What's a layout? </li><ul><li>2-step way of providing “overall” layout to your app
  25. 25. View result html will be placed as “content” in layout
  26. 26. Layout can house dynamic links for header js, css, etc
  27. 27. Easily reached from controller or view. </li></ul></ul>
  28. 28. Layout Contd. <ul><li>Create directory application/layouts and application/layouts/scripts
  29. 29. Add the following to your application.ini: </li></ul>#layout resources.layout.layout = &quot;layout&quot; resources.layout.layoutPath = APPLICATION_PATH &quot;/layouts/scripts&quot;
  30. 30. Module Layouts <ul><li>We're making an admin module
  31. 31. Let's load a specific admin layout for it </li></ul>
  32. 32. <ul>class Plugin_ModuleLayout extends Zend_Controller_Plugin_Abstract </ul>{ public function preDispatch(Zend_Controller_Request_Abstract $request) { $module = strtolower($request->getParam('module')); $layout = Zend_Layout::getMvcInstance(); if ($layout->getMvcEnabled()) { switch($module) { case 'default': break; default: $layout->setLayoutPath(APPLICATION_PATH . '/modules/' . $module . '/layouts/scripts'); break; } } } } application/plugins/ModuleLayout.php
  33. 33. Enable the plugin <ul><li>Edit application/Bootstrap.php </li></ul>public function _initLayouts() { Zend_Layout::startMvc(); $this->getPluginResource('frontcontroller') ->getFrontController() ->registerPlugin(new Plugin_ModuleLayout()); }
  34. 34. Application general layout <ul><li>applications/layouts/scripts/layout.phtml </li></ul><?php echo $this->doctype() ?> <html> <head>     <?php echo $this->headTitle() ?>     <?php echo $this->headLink() ?>     <?php echo $this->headStyle() ?>     <?php echo $this->headScript() ?> </head> <body>     <?php echo $this->layout()->content ?> </body> </html>
  35. 35. Create a User model <ul><li>application/models/DbTable/User.php </li></ul><?php class Model_DbTable_User extends Zend_Db_Table { protected $_name = 'user'; protected $_primary = 'user_id';
  36. 36. User Model Cont'd public function addUser($username, $email, $password, $user_type=1) { // generate unique id for the password salt $salt = strtolower(uniqid(rand(), true)); // and finally...one more for their initial api 'secret' key $api_secret_key = strtolower(uniqid(rand(), true)); // create a password hash to save in the database $hashed_pwd = strtolower(md5($password . $salt));
  37. 37. User Model... $data = array( 'username' => $username, 'email' => $email, 'password' => $hashed_pwd, 'salt' => $salt, 'user_type' => $user_type ); return $this->insert($data); }
  38. 38. User Model... function updateUser($id, $email, $password=null, $user_type=1) { $where = array('user_id = ?' => (int)$id); $data = array('email' => $email,'user_type'=>$user_type); if ($password !== null){ // generate unique id (again) for the password salt $salt = strtolower(uniqid(rand(), true)); $hashed_pwd = strtolower(md5($password . $salt)); $data['salt']=$salt; $data['password']=$hashed_pwd; } $this->update($data, $where); } } // End class
  39. 39. Autoloader <ul><li>Allow us to call our model class without having to include it manually </li><ul><li>In application/Bootstrap.php </li></ul></ul>public function _initAutoload() { $autoloader = new Zend_Application_Module_Autoloader( array( 'namespace'=>'', 'basePath'=>APPLICATION_PATH ) ); return $autoloader; }
  40. 40. Database Profiling in Firebug! <ul><li>Still in Bootstrap.php </li></ul>public function _initDbprofile() { if($this->getEnvironment() == 'development') { $profiler = new Zend_Db_Profiler_Firebug('All DB Queries'); $db = $this->getPluginResource('db'); $db = $db->getDbAdapter(); $profiler->setEnabled(true); $db->setProfiler($profiler); } }
  41. 41. URL Structure <ul><li>Defaults to Index controller & Index action </li><ul><li>/public/{controller}/{action}
  42. 42. /public/{module}/{controller}/{action}
  43. 43. /public/{controller} (assumes Index action)
  44. 44. /public/{controller}/{action}/{key}/{value}/{key2}/{value2}
  45. 45. /public/admin/user/edit/user_id/3 (admin = module) </li></ul></ul>
  46. 46. URL Routing <ul><li>You can create your own url structures using Zend_Controller_Router_* </li><ul><li>Many options </li><ul><li>Static
  47. 47. Regex
  48. 48. Hostname
  49. 49. Chain </li></ul><li>http://framework.zend.com/manual/en/zend.controller.router.html </li></ul></ul>
  50. 50. Create Admin Module <ul><li>Use zf tool </li><ul><li>zf create module admin </li></ul><li>Enable module in application.ini </li><ul><li>Add to [production] area
  51. 51. resources.frontController.moduleDirectory = APPLICATION_PATH “/modules” </li></ul><li>Copy application/layout/scripts/layout.phtml to application/modules/admin/layouts/scripts/layout.phtml </li></ul>
  52. 52. Create User Controller <ul><li>zf create controller user false admin
  53. 53. One small bug in zf tool: </li><ul><li>Rename admin/controllers/UserController.php to Admin_UserController.php
  54. 54. Rename class in file to Admin_UserController </li></ul></ul>
  55. 55. Create Action <ul><li>zf create action createuser user 1 admin
  56. 56. Open User controller file in an editor... </li></ul>
  57. 57. public function createuserAction() { // create form $form = new Zend_Form(); $form->setMethod('post'); $form->addElement('text','username', array( 'label' =>'User name', 'required'=>true, 'filters'=>array('StringTrim') )); $form->addElement('password','password',array( 'label'=>'Password', 'required'=>true, 'filters'=>array('StringTrim') )); $form->addElement('text','email',array( 'label'=>'Email address', 'required'=>true, 'filters'=>array('StringTrim'), 'validators'=>array('EmailAddress') )); Create a form programatically!
  58. 58. $form->addElement('captcha','captcha',array( 'label'=>'Enter the letters below', 'required'=>true, 'captcha'=>array( 'captcha'=>'Figlet', 'wordLen'=>5, 'timeout'=>300 ) )); $form->addElement('submit','Save',array( 'ignore'=>true, 'label'=>'Save New User' )); // End form
  59. 59. $request = $this->getRequest(); if($request->isPost()) { if($form->isValid($request->getPost())) { $data = $form->getValues(); $user = new Model_DbTable_User(); if($user->addUser( $data['username'], $data['email'], $data['password'],2)) // 2 for admin { $this->view->message = 'User created'; } else { $this->view->message = 'Something bad happened.'; } } } $this->view->form = $form; } // End function
  60. 60. Create View application/modules/admin/views/scripts/user/createuser.php <?php if(isset($this->message)) { ?><h1><?=$this->message ?></h1><?php } ?> Create your new user. <?php $this->form->setAction($this->url()); echo $this->form; ?>
  61. 61. Create your user! <ul><li>You should now be able to head to http://{yoursite}/admin/user/createuser
  62. 62. Try it out! </li></ul>
  63. 63. Create a login action <ul><li>Close the user controller file in your editor
  64. 64. zf create action login user 1 admin
  65. 65. Open it back up and find the loginAction method </li></ul>
  66. 66. public function loginAction() { $form = new Zend_Form(); $form->setMethod('post'); $form->addElement('text','username', array( 'label' =>'User name', 'required'=>true, 'filters'=>array('StringTrim') )); $form->addElement('password','password',array( 'label'=>'Password', 'required'=>true, 'filters'=>array('StringTrim') )); $form->addElement('submit','submit',array( 'label'=>'Login', 'ignore'=>true ));
  67. 67. $request = $this->getRequest(); $data = $request->getPost(); if($request->isPost() && $form->isValid($data)) { $u = new Model_DbTable_User(); $auth = new Zend_Auth_Adapter_DbTable($u->getAdapter() ,'user','username','password', &quot;MD5(CONCAT(?,salt)) AND user_type=2&quot; ); $auth->setIdentity($data['username'])->setCredential( $data['password'] ); $mainauth = Zend_Auth::getInstance(); $result = $mainauth->authenticate($auth); if($result->isValid()) { $this->view->message = 'You are now logged in.'; } else { $m = $result->getMessages(); $this->view->message = $m[0]; } } $this->view->form = $form; }// End function
  68. 68. Create a logout action <ul><li>Try the initial part yourself to create the action method. </li></ul>public function logoutAction() { $auth=Zend_Auth::getInstance(); $auth->clearIdentity(); $this->_redirect('/admin/user/login'); }
  69. 69. Create a login “helper” Edit application/modules/admin/views/helpers/LoginLink.php <?php class Admin_View_Helper_LoginLink extends Zend_View_Helper_Abstract { public function loginLink() { $auth = Zend_Auth::getInstance(); $front = Zend_Controller_Front::getInstance(); if($auth->hasIdentity()) { $username = $auth->getIdentity(); return &quot;Hello, $username [<a href='&quot;.$front->getBaseUrl(). &quot;/admin/user/logout'>Logout</a>]&quot;; } else { return '[<a href=&quot;'.$front->getBaseUrl(). '/admin/user/login&quot;>Login</a>]'; } } }
  70. 70. Add login helper to layout <ul><li>Edit application/modules/admin/layouts/scripts/layout.phtml </li></ul>Add before echo content: <div id= &quot;login&quot; > <?php echo $this->loginLink();?> </div> This calls the LoginLink helper we created before. Try it out: http://{yoursite}/admin/user/login
  71. 71. Enough for now <ul><li>If we got this far at the meeting, I'm amazed.
  72. 72. If not, I can continue at the next meeting. </li></ul>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×