Zend Framework 2 for Newbies
 

Zend Framework 2 for Newbies

on

  • 19,800 views

WordPress boasts a "5 minute install," wouldn't it be nice if we could get a ZF2 site up and running in less than 5 minutes? Wouldn't it be nice to be able to start using ZF2 right away without a huge ...

WordPress boasts a "5 minute install," wouldn't it be nice if we could get a ZF2 site up and running in less than 5 minutes? Wouldn't it be nice to be able to start using ZF2 right away without a huge bell curve? In this session we're going to be utilizing the ZF2 Skeleton app to show you how to quickly install and get ZF2 up and running, as well as the basics of the framework so that at the end of the session you can walk out and have your own ZF2 site up and running within minutes.

Statistics

Views

Total Views
19,800
Views on SlideShare
19,250
Embed Views
550

Actions

Likes
26
Downloads
497
Comments
0

8 Embeds 550

http://www.forfinders.com 384
http://librosweb.es 67
http://nguyendanglinh.wordpress.com 40
http://www.mikestowe.com 26
https://twitter.com 23
http://tweetedtimes.com 7
http://www.ileel2.ufu.br 2
http://forfinders.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Zend Framework 2 for Newbies Zend Framework 2 for Newbies Presentation Transcript

  • Zend Framework 2 mike stowe fornewbies October 8, 2013
  • What we’re going to talk about •  Why a PHP Framework •  Why Zend Framework 2 •  Installing Zend Framework 2 •  Zend Framework 2 Structure •  Modifying the Look and Feel of ZF2 •  Setting up Controllers/ Views •  Basic Tasks in Zend Framework 2 Ourgoal: HaveZendFramework2upand runninginlessthan5minutes!
  • What we’re NOT going to accomplish You will not leave this presentation being a Zend Framework 2 expert (unless you already are one). What you will leave being able to do is quickly install a ZF2 application based on the skeleton application, and make a basic, one module site. This talk should give you the fundamentals to help you better understand ZF2, and be able to continue learning more about the framework and the many different libraries it encapsulates. IfyouaendedintheZendFramework2 tutorialyesterday,thisprobablyisn’tforyou
  • What we’re NOT going to accomplish Also, we are focusing on efficiency and getting a running start into using Zend Framework 2. This means that we will not be covering ZF2 best practices or the “best” way to do things. This presentation is designed to empower you so that you can start working immediately with Zend Framework 2, and start digging into it more and more.
  • Important to know for this presentation •  You should be familiar with PHP 5.3 •  Basic understanding of Command Line •  You should have a basic understanding of MVC •  You should be familiar with Composer and Git •  You should understand at least basic OOP concepts
  • Who am I •  Minnesotan •  Zend Certified PHP 5.3 •  PHP Developer 10+ years •  Author, Speaker, Contributor •  Zend Framework 2 User (woot) •  Self proclaimed Dinosaur Trainer •  Developer Advocate at Constant Contact @mikegstowe @ctct_api http://developer.constantcontact.com
  • One final announcement This presentation comes complete with #hashtags… be sure to tweet at @mikegstowe or @ctct_api with them… let’s have some fun and confuse the heck out of those not in this presentation! #mikesGeingFired #twierSpam #heyItsaCow
  • Why use a PHP Framework •  Rapid Application Development •  Organization and File Structure •  Standards and Universality •  Security, Security, Security •  Large community for trouble shooting •  Code and standard advancement
  • 9 Rapid Application Development While frameworks often have a learning curve, they allow for rapid development of applications through quick installs, organized file patterns allowing cross-functional teamwork, and prebuilt libraries and utilities to help you accomplish tasks that you would otherwise need to code yourself.
  • 10 Organization and File Structure Having an organized file structure allows you to quickly locate the files you need to modify, as well as allow team members to quickly jump into your application to make changes, debug code, or perform code reviews.
  • 11 Standards and Universality Frameworks come with prebuilt standards that should be adhered to. These standards allow developers to quickly jump into projects as the main structure of the application is the same. You may go from coding a medical application to a social media platform, but the back-end is still structured the same allowing you to learn the system more quickly. Universality also makes the learning curve for new developers shorter, and provides more job opportunities for developers in general.
  • 12 Security, Security, Security Frameworks come with prebuilt libraries for managing some of the most dangerous functions within applications, including error handling, sessions, authentication, handling incoming data, data parsing, and more. These libraries are used and tested by thousands of users, reducing the likelihood that they contain vulnerabilities a single developer or small team can easily miss. Moreonsecurityatmikestowe.com/slides
  • 13 Large community Popular frameworks also have large communities that you can turn to for help if you are unsure of how to utilize a library, running into unknown bugs, or to collaborate with in building new libraries to meet your needs. Large communities also mean more, and up-to-date documentation.
  • 14 Code and Standard Advancement By working with a framework you are exposed to the latest coding standards and technologies, allowing you to grow as a developer. At the same time, as frameworks are utilized and pushed to their limits, members are able to suggest and implement new standards and functions to meet the needs of the ever changing, and rapidly growing enterprise community.
  • Popular Frameworks •  Zend Framework 2 •  Code Igniter •  Symfony 2 •  CakePHP •  Laravel •  Lithium •  Yii IusedCodeIgnitertomakeaCakePHPwhilelisteningtoa SymfonyonmyradiountilmyLithiumbaerydied,causingitto goYii. TimetodosomeyogaandreachmyZend.
  • 16 So why use Zend Framework 2 •  Service Oriented Architecture •  Strong developer community •  Online training and certification •  Used by numerous enterprise organizations •  Heavily tested with regular updates and releases •  Modular, use what you need, ignore what you don’t •  Strong use of OOP and Design Patterns for Consistency •  Security focused with built in libraries and tools •  Ideal for test-driven development •  Scalable
  • Installing Zend Framework 2 For quick, efficient installs of Zend Framework 2 we will be using Git (git-scm.com) and Composer (getcomposer.org). Git will allow us to quickly pull the latest version of the Zend Framework 2 Skeleton app from Github, while Composer will allow us to install the appropriate version of the Zend Framework Core and keep it updated. You will also need a server running PHP 5.3.3 or higher. Mod_rewrite is also recommended.
  • 18 Installing Git on Windows/ Mac You can quickly install Git on your Windows or Unix (Mac) computer by visiting http://git-scm.com/downloads and selecting the appropriate download for your operating system.
  • 19 Installing Git on Linux You can quickly install Git using the appropriate command for your Linux box: System Command Debian/Ubuntu apt-get install git Fedora yum install git Gentoo emerge --ask --verbose dev-vcs/git Arch Linux pacman -S git FreeBSD cd /usr/ports/devel/git make install Solaris 11 Express pkg install developer/versioning/git OpenBSD pkg_add git
  • 20 Installing Composer You can install Composer by visiting http://getcomposer.org/download/ or running the following Curl Command in your terminal: curl -sS https://getcomposer.org/installer | php
  • 21 Installing ZF2 in Three Simple Steps mkdir zf2 cd zf2 1. Create directory on your web server and move into it git init git remote add source https://github.com/zendframework/ZendSkeletonApplication.git git pull source master 2. Initialize Git, add the Skeleton Repository, and Download 3. Run Composer php composer.phar install
  • 22
  • 23 Installing ZF2 in Three Easy Steps
  • 24 Done! ZF2 Installed in less than 5 minutes! #lessthan5 #KayGo #yesssss #set2stun
  • 25 Your website is now ready to publish… oh wait.
  • Zend Framework 2 Structure After running the install you will see the following structure in your Application’s directory. Config contains the main config settings for the application, module contains your source code, public contains public items such as CSS, JavaScript, and images, and vendor will contain the ZF2 libraries and third party libraries.
  • 27 Zend Framework 2 Module Structure Zend Framework 2 uses the following directory structure, where Application is the module where we will be storing our code. ZF2 allows us to segment code or sections of the site in different modules.
  • 28 Modifying Layouts/ Site Template Site templates, or layouts are stored in the layout directory, found in the module/view directory.
  • 29 Controllers and Views Each Controller has it’s own views directory so that views can be created for each action. Note you can use the same view for different actions, but by default ZF2 will look for a view matching the action name unless specifically told otherwise.
  • Digging into the Code Ok, let’s dig into the code and start customizing our Zend Framework 2 project. Before we get started, it’s important to understand that ZF2 makes heavy use of Object Oriented Programming and design patterns. Zend Framework 2 also allows object chaining within the application, enabling you to perform multiple actions within a single call of the object. Ie: $this->action()->action()->action();
  • 31 Digging into the Code You can learn more about object oriented programming and design patterns from the following resources: •  http://php.net/manual/en/language.oop5.php •  http://bit.ly/19auowC •  http://bit.ly/1a5ywLb •  http://bit.ly/1bRkHDq •  http://www.phpdesignpatterns.com/ •  http://bit.ly/1fVgt2Q
  • 32 Modifying the Site Template/ Layout (HEAD) <?php echo $this->doctype(); ?> <html lang="en"> <head> <meta charset="utf-8"> <?php echo $this->headTitle('ZF2 '. $this->translate('Skeleton Application'))->setSeparator(' - ')- >setAutoEscape(false); ?> <?php echo $this->headMeta() ->appendName('viewport', 'width=device-width, initial-scale=1.0') ->appendHttpEquiv('X-UA-Compatible', 'IE=edge'); ?> <!-- Le styles --> <?php echo $this->headLink(array('rel' => 'shortcut icon', 'type' => 'image/vnd.microsoft.icon', 'href' => $this->basePath() . '/img/favicon.ico')) ->prependStylesheet($this->basePath() . '/css/style.css') ->prependStylesheet($this->basePath() . '/css/bootstrap-theme.min.css') ->prependStylesheet($this->basePath() . '/css/bootstrap.min.css'); ?> <!-- Scripts --> <?php echo $this->headScript() ->prependFile($this->basePath() . '/js/bootstrap.min.js') ->prependFile($this->basePath() . '/js/jquery.min.js'); ?> </head> ! /module/Application/view/layout/layout.phtml
  • 33 In the HEAD section of the layout you will find the following method calls. These methods allow you to control these items outside of the layout itself, making it easy to modify/ prepend/ append, or delete items. Modifying the Site Template/ Layout (HEAD) Method Action/ Functionality $this->doctype() Handles the document type $this->headTitle() Handles the document title $this->headMeta() Handles the meta data $this->headLink() Handles links/ stylesheets (css) $this->headScript() Handles scripts in header (js)
  • 34 Modifying the Site Template/ Layout (HEAD) <?php echo $this->doctype(); ?> <html lang="en"> <head> <meta charset="utf-8"> <?php echo $this->headTitle('ZF2 '. $this->translate('Skeleton Application'))->setSeparator(' - ')- >setAutoEscape(false); ?> <?php echo $this->headMeta() ->appendName('viewport', 'width=device-width, initial-scale=1.0') ->appendHttpEquiv('X-UA-Compatible', 'IE=edge'); ?> <!-- Le styles --> <?php echo $this->headLink(array('rel' => 'shortcut icon', 'type' => 'image/vnd.microsoft.icon', 'href' => $this->basePath() . '/img/favicon.ico')) ->prependStylesheet($this->basePath() . '/css/style.css') ->prependStylesheet($this->basePath() . '/css/bootstrap-theme.min.css') ->prependStylesheet($this->basePath() . '/css/bootstrap.min.css'); ?> <!-- Scripts --> <?php echo $this->headScript() ->prependFile($this->basePath() . '/js/bootstrap.min.js') ->prependFile($this->basePath() . '/js/jquery.min.js'); ?> </head> ! Let’slookatwhat’shappeningintheHEADsection
  • 35 Modifying the Site Template/ Layout (BODY) <body> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="<?php echo $this->url('home') ?>"><img src="<?php echo $this- >basePath('img/zf2-logo.png') ?>" alt="Zend Framework 2"/>&nbsp;<?php echo $this- >translate('Skeleton Application') ?></a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="<?php echo $this->url('home') ?>"><?php echo $this->translate('Home') ?></a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container"> <?php echo $this->content; ?> <hr> <footer> <p>&copy; 2005 - <?php echo date('Y') ?> by Zend Technologies Ltd. <?php echo $this->translate('All rights reserved.') ?></p> </footer> </div> <!-- /container --> <?php echo $this->inlineScript() ?> </body>! /module/Application/view/layout/layout.phtml
  • 36 In the BODY section of the layout you will find the following method calls. These methods allow you to make a layout that is dynamic and universal, controlling output through the controller and views. Modifying the Site Template/ Layout (BODY) Method Action/ Functionality $this->basePath() The base path for url/ link purposes $this->url() Gets a url based on route key/ params $this->translate() Translate text based on language, default EN $this->content() Handles the view content outputted to user $this->inlineScript() Handles inline scripts
  • 37 Modifying the Site Template/ Layout (BODY) Let’slookatwhat’shappeningintheBODYsection <body> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="<?php echo $this->url('home') ?>"><img src="<?php echo $this- >basePath('img/zf2-logo.png') ?>" alt="Zend Framework 2"/>&nbsp;<?php echo $this- >translate('Skeleton Application') ?></a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="<?php echo $this->url('home') ?>"><?php echo $this->translate('Home') ?></a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container"> <?php echo $this->content; ?> <hr> <footer> <p>&copy; 2005 - <?php echo date('Y') ?> by Zend Technologies Ltd. <?php echo $this->translate('All rights reserved.') ?></p> </footer> </div> <!-- /container --> <?php echo $this->inlineScript() ?> </body>!
  • 38 Changing the Layout Yes,Iknow…thisishorrible… #horrible #vintage #90sChick <?php echo $this->doctype(); ?> <html lang="en"> <head> <meta charset="utf-8"> <?php echo $this->headTitle($this->translate('New Layout')); ?> <!-- Should probably put some CSS in here --> <!-- And maybe some JavaScript too --> </head> <body> <h1><?php echo $this->translate('My Template'); ?></h1> <h4><?php echo $this->translate('This is a horrible template'); ?></h4> <hr /> <marquee><?php echo $this->translate('Marquee!!!'); ?></marquee> <hr /> <?php echo $this->content; ?> <hr /> <?php echo $this->translate('All rights reserved.'); ?> <?php echo $this->inlineScript() ?> </body> </html> !
  • 39 Changing the Layout
  • 40 Changing Translations #iSpeakBeiber #klingonMyWorld #habloEspaniol #moo Because we are using the translate method before outputting our text in the layout, we can update the text in the appropriate language .po file using Poedit and it will be reflected in the layout (the .mo file is automatically updated for us). This allows us to use a single layout for multiple languages. You can find the language files in the language directory of your module.
  • 41 Changing Translations "Report-Msgid-Bugs-To: n" "Language: n" "MIME-Version: 1.0n" "Content-Type: text/plain; charset=UTF-8n" "Content-Transfer-Encoding: 8bitn" "X-Poedit-KeywordsList: translaten" "X-Poedit-Language: Englishn" "X-Poedit-Country: UNITED STATESn" "X-Poedit-Basepath: .n" "X-Poedit-SearchPath-0: ..n" #: ../view/layout/layout.phtml:6 #: ../view/layout/layout.phtml:33 msgid "Skeleton Application" msgstr "" #: ../view/layout/layout.phtml:50 msgid "All rights reserved." msgstr ""! "Report-Msgid-Bugs-To: n" "Language: n" "MIME-Version: 1.0n" "Content-Type: text/plain; charset=UTF-8n" "Content-Transfer-Encoding: 8bitn" "X-Poedit-KeywordsList: translaten" "X-Poedit-Language: Englishn" "X-Poedit-Country: UNITED STATESn" "X-Poedit-Basepath: .n" "X-Poedit-SearchPath-0: ..n" #: ../view/layout/layout.phtml:6 #: ../view/layout/layout.phtml:33 msgid "Skeleton Application" msgstr "" #: ../view/layout/layout.phtml:50 msgid "All rights reserved." msgstr "Copy Freely – it sucks"!
  • 42 Changing Translations
  • Jumping into the MVC Now that we have modified the layout and know how to update the general look and feel of our website, let’s take a look at the MVC (Model, View, Controller) aspect of Zend Framework 2. We will initially be putting most of our working code in the controller to explain how things work, but keep in mind that Zend Framework 2 is Service Oriented, so it would be best to create a service that we can call in to handle these actions and reduce the amount of code we have in our controllers. #models #vampies #chickens
  • 44 Looking at the Controller <?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ApplicationController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class IndexController extends AbstractActionController { public function indexAction() { return new ViewModel(); } } ! /module/Application/src/Application/Controller/IndexController.php
  • 45 Looking at the Controller Because we’re not really doing anything, the controller is pretty empty. However there are some pretty crucial parts: 1.  We’re pulling in the AbstractActionController and ViewModel classes 2.  The indexAction() method that is called when accessing the site. This method is called because we are routing “/” to the Application module, IndexController, and index/index.phtml view 3.  We are sending a View Model to tell ZF2 how to handle views for this action. The default is the standard ViewModel, but we could also send back JSON, XML, or just return plain text (terminal).
  • 46 Looking at the Controller <?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ApplicationController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class IndexController extends AbstractActionController { public function indexAction() { return new ViewModel(); } } ! /module/Application/src/Application/Controller/IndexController.php
  • 47 Looking at the Controller We can also send variables to the view by placing them in an array, and putting that array in the ViewModel. return new ViewModel(array(‘key’=>’value’)); We can also use the setVariable() method, which gives you more freedom in how you set the variables. $view = new ViewModel(); $view->setVariable(‘key’, ‘value’);
  • 48 Looking at the Controller namespace ApplicationController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class IndexController extends AbstractActionController { public function indexAction() { $view = new ViewModel(); $view->setVariable('userName', 'guest'); if (isset($_POST['name'])) { $view->setVariable('userName', htmlspecialchars($_POST['name'])); } return $view; } } !
  • 49 Modifying the View Now if we go to our view (module/Application/view/ application/index/index.phtml) and change the code to: We should see $this->userName echo out “guest” assuming that “name” hasn’t been sent to the site via a POST request. <p>Welcome <?php echo $this->userName; ?> to my website</p>! YesIknow,mysuckysitejustgotworse…
  • 50 Modifying the View
  • 51 Showing only the View (No layout) Let’s say we wanted to only display what was in the view, instead of having it wrapped by the layout. For example, if you wanted to return just the HTML in your view script for use by an AJAX call. We can do this by using the $view->setTerminal() method and setting it to true in our controller. Note,thedefaultforthesetTerminal()methodisfalse
  • 52 Showing only the View (No layout) namespace ApplicationController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class IndexController extends AbstractActionController { public function indexAction() { $view = new ViewModel(); $view->setTerminal(true); $view->setVariable('userName', 'guest'); if (isset($_POST['name'])) { $view->setVariable('userName', htmlspecialchars($_POST['name'])); } return $view; } } !
  • 53 Showing only the view (No layout)
  • 54 Handling incoming Data in Zend Framework 2 Zend Framework 2 also has several convenient methods for checking/ using incoming POST/GET data. Instead of relying on the $_POST and $_GET SuperGlobals, Zend Framework 2 takes the guessing out of it and also provides mechanisms for increased security (especially with forms). #randomHashTag
  • 55 Handling incoming Data in Zend Framework 2 To get incoming data sent via GET we can use: $this->getRequest()->getQuery(’name', ’default’); And to get incoming POST data: $this->getRequest()->getPost('name', ’default');
  • 56 Handling incoming Data in Zend Framework 2 namespace ApplicationController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class IndexController extends AbstractActionController { public function indexAction() { $view = new ViewModel(); $view->setVariable('userName', 'guest'); if (($name = $this->getRequest()->getPost('name', false))) { $view->setVariable('userName', htmlspecialchars($name)); } return $view; } }!
  • Adding more pages Now chances are that you want more than one page on your site. We can build new pages quickly and easily within the indexController simply by adding new actions and corresponding view scripts. We can also create new controllers with new views, and we can assign custom urls to these different views by adding routes in our config file. #wereWritingaBook #TheHobbit #Twilight #Garfield
  • 58 Creating a new Action in the indexController public function indexAction() { $view = new ViewModel(); $view->setTerminal(true); $view->setVariable('userName', 'guest'); if (isset($_POST['name'])) { $view->setVariable('userName', htmlspecialchars($_POST['name'])); } return $view; } public function aboutAction() { return new ViewModel(); } !
  • 59 Creating a new view script file We then create a new view script called “about.phtml” in the appropriate directory (in this case Application/view/ application/index/ That’s all there is to it! We can now customize it like we did the index.phtml file!
  • 60 Creating new controllers & view sets Creating a new controller and view set is extremely easy in Zend Framework 2. First we create a new file, in this case called “calendarController.php” in the src/Application/Controller directory. We also create a new directory in the view/application directory called calendar where we will store the view scripts for this controller.
  • 61 The calendarController.php file <?php namespace ApplicationController; use ZendMvcControllerAbstractActionController; use ZendViewModelViewModel; class CalendarController extends AbstractActionController { public function indexAction() { return new ViewModel(); } } !
  • 62 Updating the invokable controllers list To help with script security, ZF2 contains a list of invokable controllers in the module.config.php file. We will need to update this.
  • 63 'controllers' => array( 'invokables' => array( 'ApplicationControllerIndex' => 'ApplicationControllerIndexController', 'ApplicationControllerCalendar' => 'ApplicationControllerCalendarController' ), ),! Updating the invokable controllers list By adding the following line the controller can be invoked when called via a route:
  • 64 Creating new routes Routes are also stored in the module.config.php file found in the config directory. In this file you can modify existing routes and add new routes.
  • 65 Adding a literal route 'routes' => array( 'home' => array( 'type' => 'ZendMvcRouterHttpLiteral', 'options' => array( 'route' => '/', 'defaults' => array( 'controller' => 'ApplicationControllerIndex', 'action' => 'index', ), ), ), ),!
  • 66 Adding a literal route 'routes' => array( 'home' => array( 'type' => 'ZendMvcRouterHttpLiteral', 'options' => array( 'route' => '/', 'defaults' => array( 'controller' => 'ApplicationControllerIndex', 'action' => 'index', ), ), ), 'calendar' => array( 'type' => 'ZendMvcRouterHttpLiteral', 'options' => array( 'route' => '/calendar', 'defaults' => array( 'controller' => 'ApplicationControllerCalendar', 'action' => 'index', ), ), ), ),!
  • 67 Adding a segmented route 'home' => array( 'type' => 'ZendMvcRouterHttpLiteral', 'options' => array( 'route' => '/', 'defaults' => array( 'controller' => 'ApplicationControllerIndex', 'action' => 'index', ), ), ), 'calendar' => array( 'type' => 'Segment', 'options' => array( 'route' => '/[:controller[/:action]]', 'constraints' => array( 'controller' => '[a-zA-Z][a-zA-Z0-9_-]*', 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', ), 'defaults' => array( 'action' => 'index', ), ), ),!
  • 68 Don’t worry… #endIsNear #heDoesntShutup #homerDrools
  • Doing more… By now you should be able to build a fairly simple website using Zend Framework 2. But Zend Framework isn’t just meant for simple sites, but contains the tools and libraries needed to build enterprise solutions. These libraries include tools to build forms, send emails, handle sessions, databases, internationalization, APIs, send SMS/ push notifications, and more. In the next few slides we’ll take a look at some of these tools (as time permits).
  • 70 Forms Zend Framework 2 has a powerful forms library that includes many different types of form elements, as well as the ability to add filters (sanitizers) and validators. To get started building a form, create a file with the name of your form (ie scheduleRequestForm) in the forms directory (ie: src/Application/Form). This directory does not exist by default so you will need to create it.
  • 71 Forms Having this separate directory for your forms makes it quick and easy to find and update forms within your site.
  • 72 The form code <?php namespace ApplicationForm; use ZendFormForm; class ScheduleRequestForm extends Form { public function __construct($name = null) { // we want to ignore the name passed parent::__construct('scheduleRequest'); $this->setAttribute('method', 'post'); $this->add(array( 'name' => 'firstName', 'attributes' => array( 'type' => 'text', ), 'options' => array( 'label' => 'First Name', ), ));
  • 73 Using in the controller use ZendViewModelViewModel; use ApplicationFormScheduleRequestForm; class IndexController extends AbstractActionController { public function indexAction() { $view = new ViewModel(); $form = new ScheduleRequestForm(); $request = $this->getRequest(); if ($request->isPost()) { /** Handle data **/ return $this->redirect()->toRoute('success'); } $view->setVariable('form', $form); return $view; }! #lionKing #simba #mufasa #lilemermaid #squirrel
  • 74 Using in the controller use ZendViewModelViewModel; use ApplicationFormScheduleRequestForm; class IndexController extends AbstractActionController { public function indexAction() { $view = new ViewModel(); $form = new ScheduleRequestForm(); $request = $this->getRequest(); if ($request->isPost()) { /** Handle data **/ return $this->redirect()->toRoute('success'); } $view->setVariable('form', $form); return $view; }!
  • 75 Echoing in the view <h3><?php echo $this->translate('Schedule Request'); ?></h3> <?php $form = $this->form; $form->setAttribute('action', $this->url('home', array('action' => 'add'))); $form->prepare(); echo $this->form()->openTag($form); echo $this->formRow($form->get('firstName')); echo $this->formRow($form->get('lastName')); echo $this->formRow($form->get('dateRequested')); echo $this->formSubmit($form->get('submit')); echo $this->form()->closeTag();!
  • 76 Forms #youWillSubmit #goodForm #rabbitOfDoom
  • Sessions Zend makes starting and storing session data extremely easy using the ZendSessionContainer class: use ZendMvcControllerAbstractActionController; use ZendSessionContainer; use ZendViewModelViewModel; class CalendarController extends AbstractActionController { public function indexAction() { $session = new Container('session_storage_key'); /** … **/ } } !
  • 78 Handling sessions use ZendMvcControllerAbstractActionController; use ZendSessionContainer; use ZendViewModelViewModel; class CalendarController extends AbstractActionController { public function indexAction() { $session = new Container('session_storage_key'); if (!$session->name) { $session->name = 'guest'; } return new ViewModel(array('userName' => $session->name)); } } !
  • 79 Removing sessions use ZendMvcControllerAbstractActionController; use ZendSessionContainer; use ZendViewModelViewModel; class CalendarController extends AbstractActionController { public function logoutAction() { $session = new Container('session_storage_key'); $session->getManager()->getStorage()->clear('session_storage_key'); } }! You can delete all $_SESSION data by using unset($_SESSION) or clear specific session data by calling the Session Manager and clearing the storage as shown here:
  • Is he done yet?!? #isThataHorse #windowPain #hoofingIt #LifesNotMare
  • 81 Even more power Zend Framework 2 has a lot of very powerful and useful services built into it that we just do not have the time to talk about. These include the ServiceLocator also referred to as the ServiceManager and the EventManager. As you continue to develop using Zend Framework 2 you will become more and more used to these two powerful tools, how they are used, and more comfortable working with them. But again, the point of this session was to give you the quick (and ugly) way of doing things to expose you to the framework, and allow you to get your site up and running right away.
  • 82 Continuing on… So now I want to encourage you to go out, take what you’ve learned here, and start playing with Zend Framework 2. Test it out for yourselves, push the framework and your skills to their limits. There is a great online community that is more than willing to help! And if the going gets tough (because there is a learning curve), just remember to…
  • 83 Continuing on… Or stare at cat pictures on the internet… that works too. In the meantime, here are some helpful resources to learn more about Zend Framework 2. #postiveThinking
  • More Resources Zend Framework 2 – Getting Started Guide: http://framework.zend.com/manual/2.1/en/user-guide/overview.html Zend Framework Reference Guide: http://framework.zend.com/manual/2.1/en/index.html Building a REST API with ZF2: http://www.slideshare.net/mikestowe/building-a-rest-api-with-zend-framework-2
  • THANK YOU!!! Please be sure to let me know you think by tweeting me at @CTCT_API or @mikegstowe Also a special thanks to Constant Contact (@ConstantContact) for letting me do this talk and their support of ZendCon and the PHP community. Slidespostedonlineathp://www.mikestowe.com/slides