Zend Framework Development Introduction Classic Tutorial _php Example

Source: Internet
Author: User
Tags php class php foreach php script php template sqlite zend zend framework

This article describes the introduction of Zend Framework development related knowledge points. Share to everyone for your reference, specific as follows:

The Zend framework has been released! While still in the early stages of development, this tutorial still highlights several of the best features of the present and guides you through the construction of a simple program.

Zend first launched the ZF in the community. Based on the same idea, this tutorial is written to show the ZF existing functionality. Since this tutorial is published online, I will update it as the ZF changes to be as effective as possible.

Requirements

The Zend framework requires PHP5. To make better use of the code for this tutorial, you will also need the Apache Web server. Because the model program (a news management system) used mod_rewrite.

The code for this tutorial is free to download, so you can try it yourself. You can download the code from Brain Buld's website: http://brainbulb.com/zend-framework-tutorial.tar.gz.

Download ZF

When you start this tutorial, you will need to download the latest version of ZF. You can use the browser to manually select tar.gz or zip files from http://framework.zend.com/download to download, or use the following command:

$ wget http://framework.zend.com/download/tgz
$ tar-xvzf zendframework-0.1.2.tar.gz

Tip: Zend plans to provide a simplified download of its own pear channel.

Once you have downloaded the preview version, place the library directory where it is convenient. In this tutorial, I rename the library to Lib to have a concise directory structure:

app/
views/
controllers/
www/
. htaccess
index.php
lib/

The WWW directory is the document root, and the controllers and views directory is an empty directory to be used later, and the Lib directory is from the preview version you downloaded.

Begin

The first component I want to introduce is zend_controller. In many ways, it provides a foundation for the programs you develop, and it also partly determines that the Zend framework is not just a collection of components. However, before you use it, you need to put all your requests in a simple PHP script. This tutorial is for mod_rewrite.

Using Mod_rewrite itself is an art, but fortunately, this particular task is particularly simple. If you are unfamiliar with the general configuration of Mod_rewrite or Apache, create a. htaccess file in the root of the document and add the following:

Rewriteengine on
rewriterule!/. ( JS|ICO|GIF|JPG|PNG|CSS) $ index.php

Hint: One of the Todo items in Zend_controller is to cancel the dependency on mod_rewrite. To provide an example of a preview version, this tutorial uses mod_rewrite.

If you add this content directly to httpd.conf, you must restart the Web server. But if you use a. htaccess file, you don't have to do anything. You can put some concrete text into the index.php and access any path such as/foo/bar to do a quick test. If your domain name is example.org, then visit Http://example.org/foo/bar.

You also have to set the path of the ZF Library to Include_path. You can set it in php.ini, or you can put the following in your. htaccess file directly:

Php_value include_path "/path/to/lib"

Zend

The Zend class contains a collection of static methods that are often used. Here's the only class you want to add manually:

<?php
include ' zend.php ';
? >

Once you include the zend.php, you have already included all the class methods of the Zend class. You can simply load other classes with LoadClass (). For example, load the Zend_controller_front class:

<?php
include ' zend.php ';
Zend::loadclass (' Zend_controller_front ');
? >

Include_path can understand the organization and directory structure of LoadClass () and ZF. I use it to load all the other classes.

Zend_controller

Using this controller is very intuitive. In fact, I didn't use its rich documentation when I wrote the tutorial.

Hint: The document is now available in http://framework.zend.com/manual/zend.controller.html.

I started out with a front Controller called Zend_controller_front. To understand how it works, please put the following code in your index.php file:

<?php
include ' zend.php ';
Zend::loadclass (' Zend_controller_front ');
$controller = Zend_controller_front::getinstance ();
$controller->setcontrollerdirectory ('/path/to/controllers ');
$controller->dispatch ();
? >

If you prefer object chaining, you can use the following code instead:

<?php
include ' zend.php ';
Zend::loadclass (' Zend_controller_front ');
$controller = Zend_controller_front::getinstance ()
       ->setcontrollerdirectory ('/path/to/controllers ')
       ->dispatch ();
? >

Now if you visit/foo/bar, there will be errors. That's right! It lets you know what's going on. The main problem is that the indexcontroller.php file cannot be found.

Before you create this file, you should first understand how the ZF wants you to organize these things. The ZF split the request for access. If the access is/foo/bar, Foo is controller and bar is the action. Their default values are index.

If Foo is CONTROLLER,ZF, it will look for foocontroller.php files in the Controllers directory. As the document does not exist, the ZF returns to indexcontroller.php. None of the results were found and the error was made.

Next, create the indexcontroller.php file in the Controllers directory (can be set with Setcontrollerdirectory ()):

<?php
zend::loadclass (' zend_controller_action ');
Class Indexcontroller extends zend_controller_action 
{public
  function indexaction ()
  {
    echo ' Indexcontroller::indexaction () ';
  }
? >

As explained earlier, the Indexcontroller class handles requests that do not exist from the index controller or controller. The Indexaction () method handles the access of the action to index. Keep in mind that index is the default value for controller and action. If you access the/,/index or/index/index,indexaction () method, it will be executed. (The last slash does not change this behavior.) and access to any other resource will only cause an error.

Before you proceed, add another useful class method to the Indexcontroller. Whenever you access a non-existent controller, call the Norouteaction () class method. For example, if the foocontroller.php does not exist, the access/foo/bar executes Norouteaction (). But accessing/index/foo still goes wrong because Foo is the action, not the controller.

Add Norouteaction () to indexcontroller.php:

<?php
zend::loadclass (' zend_controller_action ');
Class Indexcontroller extends zend_controller_action 
{public
  function indexaction ()
  {
    echo ' Indexcontroller::indexaction () ';
  }
  Public Function norouteaction ()
  {
    $this->_redirect ('/');
  }
? >

The example uses $this->_redirect ('/') to describe the behavior that may occur when executing norouteaction (). This redirects access to the controllers to the root document (home page).

Now create foocontroller.php:

<?php
zend::loadclass (' zend_controller_action ');
Class Foocontroller extends zend_controller_action 
{public
  function indexaction ()
  {
    echo ' Foocontroller::indexaction () ';
  }
  Public Function baraction ()
  {
    echo ' foocontroller::baraction () ';
  }
}
? >

If you visit/foo/bar again, you will notice that baraction () is executed because bar is the action. Now you not only support friendly URLs, but you can do so methodically with just a few lines of code. It's cool!
You can also create a __call () class method to handle an undefined action like/foo/baz.

<?php
zend::loadclass (' zend_controller_action ');
Class Foocontroller extends zend_controller_action 
{public
  function indexaction ()
  {
    echo ' Foocontroller::indexaction () ';
  }
  Public Function baraction ()
  {
    echo ' foocontroller::baraction () ';
  }
  Public Function __call ($action, $arguments)
  {
    echo ' foocontroller:__call () ';
  }
}
? >

Now you just need a few lines of code to handle the user's access well and be ready to continue.

Zend_view

Zend_view is a class designed to help you organize your view logic. This is not known for templates-systems, and for simplicity, this tutorial does not use templates. If you like, you might as well use it.

Remember, all the visits are now handled by front Controller. So the application framework already exists, and it must also be adhered to. To demonstrate a basic application of Zend_view, the indexcontroller.php is modified as follows:

<?php
zend::loadclass (' zend_controller_action ');
Zend::loadclass (' Zend_view ');
Class Indexcontroller extends zend_controller_action 
{public
  function indexaction ()
  {
    $view = new Zend_view ();
    $view->setscriptpath ('/path/to/views ');
    echo $view->render (' example.php ');
  }
  Public Function norouteaction ()
  {
    $this->_redirect ('/');
  }
? >

Create a example.php file in the views directory:

 
 

Now, if you visit the root resources of your site, you will see the example.php content. It's still useless, but you need to be aware that you are developing Web applications in a way that is very clear in structure and organization.

To make the application of Zend_view clearer, modify your template (example.php) to include the following:

 
 

Two features have now been added. $this->escape () class method is used for all output. Even if you create the output yourself, just like this example. Avoiding all of the output is also a good habit, and it can help you prevent Cross-site scripting attacks (XSS) by default.

$this->title and $this->body properties are used to display dynamic data. These can also be defined in controller, so we modify indexcontroller.php to specify them:

<?php
zend::loadclass (' zend_controller_action ');
Zend::loadclass (' Zend_view ');
Class Indexcontroller extends zend_controller_action 
{public
  function indexaction ()
  {
    $view = new Zend_view ();
    $view->setscriptpath ('/path/to/views ');
    $view->title = ' Dynamic title ';
    $view->body = ' This is a dynamic body. '
    echo $view->render (' example.php ');
  }
  Public Function norouteaction ()
  {
    $this->_redirect ('/');
  }
? >

Now that you have access to the root directory again, you should be able to see the values that the template uses. Because the $this you use in the template is the instance that executes in the Zend_view scope.

Remember that example.php is just an ordinary PHP script, so you can do what you want. Just try to use the template only when you want to display the data. Your controller (Controller distributed module) should handle all of your business logic.

Before I go on, I want to make one last hint about Zend_view. Initializing the $view object in each of the Controller's class methods requires additional input, and our main goal is to make rapid development network applications simpler. If all the templates are placed in a single directory, it is debatable whether you want to call Setscriptpath () in each case.

Fortunately, the Zend class contains a register to help reduce workload. You can use the register () method to store your $view objects in registers:

<?php
zend::register (' View ', $view);
? >

To retrieve using the registry () method:

<?php
$view = zend::registry (' view ');
? >

Based on this, the tutorial uses registers.

Zend_inputfilter

The last component discussed in this tutorial is zend_inputfilter. This class provides a simple and efficient method of input filtering. You can initialize by providing a set of data to be filtered.

<?php
$filterPost = new Zend_inputfilter ($_post);
? >

This sets ($_post) to NULL, so it cannot be entered directly. Zend_inputfilter provides a simple, centralized set of class methods that filter data based on specific rules. For example, you can use Getalpha () to get the letters in $_post[' name ':

<?php
/* $_post[' name ' = ' john123doe '; */
$filterPost = new Zend_inputfilter ($_post);
/* $_post = NULL; * *
$alphaName = $filterPost->getalpha (' name ');
/* $alphaName = ' JohnDoe '; * *
?>

The parameters of each class method are the keywords that correspond to the elements to be filtered. Objects ($filterpost in the example) can protect data from tampering and better control the operation and consistency of data. Therefore, when you manipulate input data, you should always use Zend_inputfilter.

Tip: Zend_filter provides the same static method as the Zend_inputfilter method.

Building News Management System

Although the preview provides a number of components (and even many have been developed), we have discussed all the components needed to build a simple program. Here, you will have a clearer understanding of the basic structure and design of ZF.

The programs that everyone develops are different, and the Zend Framework tries to accommodate these differences. Again, this tutorial is written according to my preference, please adjust yourself according to your preference.

When I develop the program, I will do the interface first. That doesn't mean I spend my time on labels, stylesheets, and pictures, but I think about things from a user's point of view. So I think of the program as a collection of pages, each page is a separate URL. The news system is made up of the following Web sites:

/
/add/news
/add/comment
/admin
/admin/approve
/view/{id}

You can link these URLs directly to the controller. Indexcontroller lists news, Addcontroller adds news and comments, Admincontroller deals with management such as approving news, Viewcontroller specific news and corresponding comments.

If your foocontroller.php is still there, remove it. Modify the indexcontroller.php to add the appropriate action and some comments for the business logic:

<?php
zend::loadclass (' zend_controller_action ');
Class Indexcontroller extends zend_controller_action 
{public
  function indexaction ()
  {/
    * List the News. *
  /} public
  function norouteaction ()
  {
    $this->_redirect ('/');
  }
? >

Next, create the addcontroller.php file:

<?php
zend::loadclass (' zend_controller_action ');
Class Addcontroller extends zend_controller_action
{
  function indexaction ()
  {
    $this->_ Redirect ('/');
  }
  function commentaction ()
  {/
    * Add a comment. */
  }
  function newsaction ()
  {/
    * Add news. */*
  }
  function __call ($action, $arguments)
  {
    $this->_redirect ('/');
  }
? >

Remember that the Addcontroller indexaction () method cannot be invoked. This class method is executed when accessing/add. Because users can manually access this URL, it is possible, so you have to redirect users to the home page, display errors or you think the appropriate behavior.

Next, create the admincontroller.php file:

<?php
zend::loadclass (' zend_controller_action ');
Class Admincontroller extends zend_controller_action
{
  function indexaction ()
  {/
    * Display admin Interface. */
  }
  function approveaction ()
  {/
    * Approve news.
  }
  function __call ($action, $arguments
  {
    $this->_redirect ('/');
  }
? >

Finally, create the viewcontroller.php file:

<?php
zend::loadclass (' zend_controller_action ');
Class Viewcontroller extends zend_controller_action
{
  function indexaction ()
  {
    $this->_ Redirect ('/');
  }
  function __call ($id, $arguments)
  {/
    * Display News and comments for $id. *}
}
?>

As with Addcontroller, the index () method cannot be invoked, so you can use the action you think is appropriate. Viewcontroller is a little different from the others because you don't know what a valid action is. To support URLs like/VIEW/23, you use __call () to support dynamic action.

Database operations

Because the database components of the Zend Framework are still unstable, I hope this demo can be done a little easier. I used a simple class that used SQLite to store and query news items and comments.

&lt;?php class Database {private $_db;
  Public function __construct ($filename) {$this-&gt;_db = new Sqlitedatabase ($filename);
    The Public Function addcomment ($name, $comment, $newsId) {$name = sqlite_escape_string ($name);
    $comment = sqlite_escape_string ($comment);
    $newsId = sqlite_escape_string ($newsId);
    $sql = "INSERT into comments (name, comment, newsId) VALUES (' $name ', ' $comment ', ' $newsId ')";
  return $this-&gt;_db-&gt;query ($sql);
    The Public Function addnews ($title, $content) {$title = sqlite_escape_string ($title);
    $content = sqlite_escape_string ($content);
    $sql = "INSERT into News (title, content) VALUES (' $title ', ' $content ')";
  return $this-&gt;_db-&gt;query ($sql);
      The Public Function approvenews ($ids) {foreach ($ids as $id) {$id = sqlite_escape_string ($id);
      $sql = "UPDATE news SET approval = ' T ' WHERE id = ' $id '"; if (! $this-&gt;_db-&gt;queRy ($sql)) {return FALSE;
  } return TRUE;
    The Public Function getcomments ($newsId) {$newsId = sqlite_escape_string ($newsId);
    $sql = "Select name, comment from comments WHERE newsId = ' $newsId '";
    if ($result = $this-&gt;_db-&gt;query ($sql)) {return $result-&gt;fetchall ();
  return FALSE;
    The Public function getnews ($id = ' all ') {$id = sqlite_escape_string ($id);  Switch ($id) {case ' all ': $sql = ' Select ID, title from news WHERE
        approval = ' T ' ";
      Break
        Case ' NEW ': $sql = "SELECT * FROM news WHERE approval!= ' T '";
      Break
        Default: $sql = "SELECT * FROM news WHERE id = ' $id '";
    Break } if ($result = $this-&gt;_db-&gt;query ($sql)) {if ($result-&gt;numrows ()!= 1) {return $result-&gt;fe
      Tchall (); else {return $resuLt-&gt;fetch ();
  return FALSE;

 }}?&gt;

(You can replace this class with your own solution.) This is just an introduction to a complete sample, not a recommended implementation. )

The constructor for this class needs to sqlite the full path and file name of the database, and you must create it yourself.

<?php
$db = new Sqlitedatabase ('/path/to/db.sqlite ');
$db->query ("CREATE TABLE News" (
    ID    INTEGER PRIMARY KEY,
    title  VARCHAR (255),
    content TEXT,
    approval CHAR (1) DEFAULT ' F ')
  ");
$db->query ("CREATE TABLE comments" (
    ID    INTEGER PRIMARY KEY,
    name   VARCHAR (255),
    comment TEXT,
    newsId  INTEGER
  ) ");
? >

You just have to do it once, and then give the full path and filename of the database class builder directly:

<?php
$db = new Database ('/path/to/db.sqlite ');
? >

Integration

For consolidation, you can find it by creating a database.php,loadclass () in the Lib directory. Your index.php files will now initialize $view and $db and store them in registers. You can also create __autoload () functions to automatically load the classes you need:

<?php
include ' zend.php ';
function __autoload ($class)
{
  zend::loadclass ($class);
}
$db = new Database ('/path/to/db.sqlite ');
Zend::register (' db ', $db);
$view = new Zend_view;
$view->setscriptpath ('/path/to/views ');
Zend::register (' View ', $view);
$controller = Zend_controller_front::getinstance ()
       ->setcontrollerdirectory ('/path/to/controllers ')
       ->dispatch ();
? >

Next, create some simple templates in the views directory. Index.php can be used to display the index view:

 
 

The view.php template can be used to display selected news items:

&lt;html&gt; &lt;head&gt; &lt;title&gt; &lt;?php echo $this-&gt;escape ($this-&gt;news[' title ');?&gt; &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; &lt;?php echo $this-&gt;escape ($this-&gt;news[' title ');?&gt; &lt;/h1&gt; ;p &gt; &lt;?php echo $this-&gt;escape ($this-&gt;news[' content ');?&gt; &lt;/p&gt; &lt;h1&gt;Comments&lt;/h1&gt; &lt;  ? php foreach ($this-&gt;comments as $comment) {?&gt; &lt;p&gt; &lt;?php echo $this-&gt;escape ($comment [' name ']);?&gt; 
 Writes: &lt;/p&gt; &lt;blockquote&gt; &lt;?php echo $this-&gt;escape ($comment [' comment ']);?&gt; &lt;/blockquote&gt; &lt;?php}?&gt; &lt;h1&gt;add a comment&lt;/h1&gt; &lt;form action= "/add/comment" method= "POST" &gt; &lt;input type= " Hidden "name=" NewsId "value=" &lt;?php Echo $this-&gt;escape ($this-&gt;id);?&gt; "/&gt; &lt;p&gt;name:&lt;br/&gt;&lt; Input type= "text" name= "name"/&gt;&lt;/p&gt; &lt;p&gt;comment:&lt;br/&gt;&lt;textarea name= "Comment" &gt;&lt;/ Textarea&gt;&lt;/p&gt; &lt;p&gt;&Lt;input type= "Submit" value= "Add Comment"/&gt;&lt;/p&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;

 

Finally, the admin.php template can be used to approve news entries:

 
 

Tip: To keep it simple, the table has a password as a validation mechanism.

Where you use the template, you just need to replace the annotation with a few lines of code. such as indexcontroller.php becomes the following:

<?php
class Indexcontroller extends zend_controller_action 
{public
  function indexaction ()
  {
    /* List the news. *
    /$db = zend::registry (' db ');
    $view = Zend::registry (' view ');
    $view->news = $db->getnews ();
    echo $view->render (' index.php ');
  }
  Public Function norouteaction ()
  {
    $this->_redirect ('/');
  }
? >

Because the organization is more clear, the entire business logic of this program's home page has only four lines of code. Addcontroller.php is a bit more complicated, it requires more code:

<?php
class Addcontroller extends zend_controller_action
{
  function indexaction ()
  {
    $this- >_redirect ('/');
  }
  function commentaction ()
  {/
    * Add a comment. */
    $filterPost = new Zend_inputfilter ($_post);
    $db = zend::registry (' db ');
    $name = $filterPost->getalpha (' name ');
    $comment = $filterPost->notags (' comment ');
    $newsId = $filterPost->getdigits (' newsId ');
    $db->addcomment ($name, $comment, $newsId);
    $this->_redirect ("/view/$newsId");
  }
  function newsaction ()
  {/
    * ADD News. */
    $filterPost = new Zend_inputfilter ($_post);
    $db = zend::registry (' db ');
    $title = $filterPost->notags (' title ');
    $content = $filterPost->notags (' content ');
    $db->addnews ($title, $content);
    $this->_redirect ('/');
  }
  function __call ($action, $arguments)
  {
    $this->_redirect ('/');
  }
? >

Because the user is redirected after submitting the form, the controller does not require a view.

In admincontroller.php, you have to process the display admin interface and approve the news two action:

<?php
class Admincontroller extends zend_controller_action
{
  function indexaction ()
  {/
    * Display Admin interface. * *
    $db = zend::registry (' db ');
    $view = Zend::registry (' view ');
    $view->news = $db->getnews (' NEW ');
    echo $view->render (' admin.php ');
  }
  function approveaction ()
  {/
    * Approve News. */
    $filterPost = new Zend_inputfilter ($_post);
    $db = zend::registry (' db ');
    if ($filterPost->getraw (' password ') = = ' Mypass ') {
      $db->approvenews ($filterPost->getraw (' IDs '));
      $this->_redirect ('/');
    } else {
      echo ' password is incorrect. '
    }
  }
  function __call ($action, $arguments)
  {
    $this->_redirect ('/');
  }
? >

The last is viewcontroller.php:

<?php
class Viewcontroller extends zend_controller_action
{
  function indexaction ()
  {
    $this- >_redirect ('/');
  }
  function __call ($id, $arguments)
  {/
    * Display News and comments for $id. *
    /$id = Zend_filter::getdigits ($id );
    $db = zend::registry (' db ');
    $view = Zend::registry (' view ');
    $view->news = $db->getnews ($id);
    $view->comments = $db->getcomments ($id);
    $view->id = $id;
    echo $view->render (' view.php ');
  }
? >

Although very simple, we still provide a more full-featured news and commentary program. The best part is that with better design, adding functionality becomes very simple. And as the Zend framework matures, it will only get better.

More information

This tutorial only discusses some of the features of the ZF surface, but there are other resources available for your reference. In http://framework.zend.com/manual/there are manuals to inquire about, and Rob Allen introduces some of his experiences in http://akrabat.com/zend-framework/using the Zend Framework, Richard Thomas also provided some useful notes in http://www.cyberlot.net/zendframenotes. If you have your own ideas, you can access the new forum of the Zend Framework: http://www.phparch.com/discuss/index.php/f/289//.

Conclusion

It's easy to evaluate the preview, and I've encountered a lot of difficulties in writing this tutorial. In general, I think the Zend Framework shows promise, and everyone who joins is trying to improve it.

More interested in Zend related content readers can view the site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design based on the Zend Framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.