Getting started with ZendFramework

Source: Internet
Author: User
This article mainly introduces ZendFramework development basics and describes zend Source Code Download, environment configuration, basic component usage, and related precautions for ZendFramework development, for more information about Zend Framework development, see the following section. We will share this with you for your reference. The details are as follows:

Zend Framework released! Although it is still in the early stage of development, this tutorial still highlights several of the best features and guides you to build a simple program.

Zend first released ZF in the community. Based on the same idea, this tutorial is used to demonstrate the existing features of ZF. Since this tutorial is released online, I will update it when ZF changes to be as effective as possible.

Requirements

Zend Framework requires PHP5. To make better use of the code in this tutorial, you also need Apache Web server. Because the demo program (a News Management System) uses mod_rewrite.

The code for this tutorial can be freely downloaded, so you can try it on your own. You can download the code from the Brain Buld website: http://brainbulb.com/zend-framework-tutorial.tar.gz.

Download ZF

When you start this tutorial, you need to download the latest ZF version. You can manually download the tar.gzor zip file from http://framework.zend.com/downloadusing the following command:

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

Tip: Zend plans to provide its own PEAR channel for simplified download.

Once you download the preview version, put the library directory in a convenient place. In this tutorial, I rename the library to lib to have a simple directory structure:

App/
Views/
Controllers/
Www/
. Htaccess
Index. php
Lib/

The www directory is the root directory of the document, and the controllers and views directories are empty directories that will be used later, while the lib directory is from the preview version you downloaded.

Start

The first component I want to introduce is Zend_Controller. In many aspects, Zend Framework provides the foundation for your programs. it also determines that Zend Framework is not just a set of components. However, you need to put all the requests in a simple PHP script before using it. This tutorial uses mod_rewrite.

Using mod_rewrite itself is an art, but fortunately, this special task is very simple. If you are not familiar with the mod_rewrite or Apache configuration, create a. htaccess file under the root directory of the document and add the following content:

RewriteEngine onRewriteRule !/.(js|ico|gif|jpg|png|css)$ index.php

Tip: a todo project of Zend_Controller is to cancel the dependency on mod_rewrite. To provide a preview example, mod_rewrite is used in this tutorial.

If you directly add the content to httpd. conf, you must restart the web server. However, if you use a. htaccess file, you do not have to do anything. You can put some specific text to index. php and access any path such as/foo/bar for a quick test. If your domain name is example.org, visit http://example.org/foo/bar.

You also need to set the ZF library path to include_path. You can set it in php. ini or put the column content directly in your. htaccess file:

php_value include_path "/path/to/lib"

Zend

The Zend class contains a set of frequently used static methods. The only class you want to manually add is as follows:

<?phpinclude 'Zend.php';?>

Once you include Zend. php, you have included all the class methods of the Zend class. With loadClass (), you can simply load other classes. For example, load the Zend_Controller_Front class:

<?phpinclude '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 other classes.

Zend_Controller

This controller is very intuitive. In fact, I did not use its rich documentation when writing this tutorial.

Tip: The document can be viewed at http://framework.zend.com/manual/zend.controller.html.

I first used a front controller named Zend_Controller_Front. To understand how it works, put the following code in your index. php file:

<?phpinclude 'Zend.php';Zend::loadClass('Zend_Controller_Front');$controller = Zend_Controller_Front::getInstance();$controller->setControllerDirectory('/path/to/controllers');$controller->dispatch();?>

If you prefer object link, use the following code instead:

<?phpinclude 'Zend.php';Zend::loadClass('Zend_Controller_Front');$controller = Zend_Controller_Front::getInstance()       ->setControllerDirectory('/path/to/controllers')       ->dispatch();?>

Now, if you access/foo/bar, an error will occur. That's right! It lets you know what happened. The main problem is that the IndexController. php file cannot be found.

Before creating this file, you should first understand how ZF wants you to organize these things. ZF splits access requests. If/foo/bar is accessed, foo is the controller, and bar is the action. Their default values are index.

If foo is a controller, ZF searches for the FooController. php file under the controllers directory. Because this file does not exist, ZF will return to IndexController. php. If no result is found, an error is returned.

Next, create the IndexController. php file in the controllers Directory (you can set it with setControllerDirectory ):

<?phpZend::loadClass('Zend_Controller_Action');class IndexController extends Zend_Controller_Action {  public function indexAction()  {    echo 'IndexController::indexAction()';  }}?>

As described earlier, the IndexController class processes requests that do not exist in the index controller or controller. The indexAction () method is used to process access whose action is index. Remember that index is the default value of controller and action. If you access the/,/index or/index, the indexAction () method will be executed. (The Last slash does not change this behavior .) However, access to any other resource will only cause errors.

Before proceeding, add another useful class method to IndexController. Call the noRouteAction () method whenever you access a controller that does not exist. For example, if FooController. php does not exist, noRouteAction () is executed when/foo/bar is accessed (). However, access to/index/foo still fails because foo is action rather than controller.

Add noRouteAction () to IndexController. php:

<?phpZend::loadClass('Zend_Controller_Action');class IndexController extends Zend_Controller_Action {  public function indexAction()  {    echo 'IndexController::indexAction()';  }  public function noRouteAction()  {    $this->_redirect('/');  }}?>

In this example, $ this-> _ redirect ('/') is used to describe the behavior that may occur when noRouteAction () is executed. This redirects access to the root document (home page) that does not contain controllers ).

Now create FooController. php:

<?phpZend::loadClass('Zend_Controller_Action');class FooController extends Zend_Controller_Action {  public function indexAction()  {    echo 'FooController::indexAction()';  }  public function barAction()  {    echo 'FooController::barAction()';  }}?>

If you access/foo/bar again, you will find that barAction () is executed because bar is action. Now you not only support friendly URLs, but also just a few lines of code. Cool!
You can also create a _ call () class to process undefined actions like/foo/baz.

<?phpZend::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 only need a few lines of code to handle user access well and are ready to continue.

Zend_View

Zend_View is a class used to help you organize your view logic. This is unknown to the template-system. for simplicity, this tutorial does not use a template. Use it if you like.

Remember, all accesses are now handled by the front controller. Therefore, the application framework already exists and must comply with it. To display a basic application of Zend_View, modify IndexController. php as follows:

<?phpZend::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 the example. php file in the views Directory:

  This Is an Example  

This is an example.

Now, if you access the root resource of your website, you will see the content of example. php. This is still useless, but you need to be clear that you need to develop network applications in a very clear way of structure and organization.

To make the Zend_View application clearer, modifying your template (example. php) contains the following content:

  <?php echo $this->escape($this->title); ?>  <?php echo $this->escape($this->body); ?>

Now you have added two features. $ This-> escape () class method is used for all outputs. Even if you create your own output, just like in this example. It is also a good habit to avoid all outputs. it helps you prevent cross-site scripting (XSS) attacks by default ).

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

<?phpZend::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 you can access the root directory again to see the values used by the template. Because the $ this you use in the template is the instance executed within the Zend_View range.

Remember that example. php is just a common PHP script, so you can do what you want. The template should be used only when the data is displayed as required. Your controller should process all your business logic.

Before proceeding, I want to make the last prompt about Zend_View. To initialize the $ view object in each class method of the controller, you need to enter some additional content. our main goal is to make quick development of network applications easier. If all templates are placed in the same directory, whether to call setScriptPath () in each example is also controversial.

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

<?phpZend::register('view', $view);?>

Use the registry () method for retrieval:

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

Based on this, this tutorial uses registers.

Zend_InputFilter

The last component discussed in this tutorial is Zend_InputFilter. This class provides a simple and effective input filtering method. You can initialize a group of data to be filtered.

<?php$filterPost = new Zend_InputFilter($_POST);?>

This will set ($ _ POST) to NULL, so you cannot directly enter. Zend_InputFilter provides a simple and centralized class method set for filtering data based on specific rules. For example, you can use getAlpha () to obtain the letters in $ _ POST ['name:

<?php/* $_POST['name'] = 'John123Doe'; */$filterPost = new Zend_InputFilter($_POST);/* $_POST = NULL; */$alphaName = $filterPost->getAlpha('name');/* $alphaName = 'JohnDoe'; */?>

Parameters of each class method correspond to the keywords of the elements to be filtered. Object ($ filterPost in this example) can protect data from tampering and better control data operations and consistency. Therefore, you should always use Zend_InputFilter when manipulating input data.

Tip: Zend_Filter provides the same static method as Zend_InputFilter.

Build a news management system

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

Different programs are developed by everyone, and Zend Framework tries to accommodate these differences. Similarly, this tutorial is based on my preferences. Please adjust it based on your preferences.

When I develop a program, I will first make the interface. This does not mean that I spend all my time on tags, style sheets, and images. Instead, I will consider the problem from the perspective of a user. Therefore, I regard the program as a collection of pages, and each page is an independent Web site. This news system is composed of the following URLs:

/
/Add/news
/Add/comment
/Admin
/Admin/approve
/View/{id}

You can directly associate these URLs with the controller. IndexController lists News, AddController adds news and comments, AdminController handles management such as approval news, and ViewController displays specific news and corresponding comments.

If your FooController. php is still running, delete it. Modify IndexController. php to add corresponding actions and comments to the business logic:

<?phpZend::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:

<?phpZend::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 indexAction () method of AddController cannot be called. This class method is executed when you access/add. Because users can access this URL manually, this is possible, so you need to redirect the user to the home page, display an error or behavior that you think is appropriate.

Next, create the AdminController. php file:

<?phpZend::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:

<?phpZend::loadClass('Zend_Controller_Action');class ViewController extends Zend_Controller_Action{  function indexAction()  {    $this->_redirect('/');  }  function __call($id, $arguments)  {    /* Display news and comments for $id. */  }}?>

Like AddController, the index () method cannot be called, so you can use the action that you think is appropriate. ViewController is a little different from others, because you don't know what is a valid action. To support URLs like/view/23, use _ call () to support dynamic actions.

Database operations

Because the database components of Zend Framework are not stable, I hope this demonstration can be simpler. I used a simple class and SQLite to store and query news entries and comments.

<?phpclass Database{  private $_db;  public function __construct($filename)  {    $this->_db = new SQLiteDatabase($filename);  }  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->_db->query($sql);  }  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->_db->query($sql);  }  public function approveNews($ids)  {    foreach ($ids as $id) {      $id = sqlite_escape_string($id);      $sql = "UPDATE news          SET  approval = 'T'          WHERE id = '$id'";      if (!$this->_db->query($sql)) {        return FALSE;      }    }    return TRUE;  }  public function getComments($newsId)  {    $newsId = sqlite_escape_string($newsId);    $sql = "SELECT name, comment        FROM  comments        WHERE newsId = '$newsId'";    if ($result = $this->_db->query($sql)) {      return $result->fetchAll();    }    return FALSE;  }  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->_db->query($sql)) {      if ($result->numRows() != 1) {        return $result->fetchAll();      } else {        return $result->fetch();      }    }    return FALSE;  }}?>

(You can replace this class with your own solution. Here is just a complete example for you. we do not recommend this .)

The constructor of this class requires the complete path and file name of the SQLite database. 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 only need to do this once. then, you can directly give the complete path and file name of the Database class constructor:

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

Integration

For integration, create Database. php and loadClass () in the lib directory to find it. Your index. php file will now initialize $ view and $ db and store them in registers. You can also create the _ autoload () function to automatically load the required classes:

<?phpinclude '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:

 News News <?php foreach ($this->news as $entry) { ?> 

escape($entry['id']); ?>"> <?php echo $this->escape($entry['title']); ?>

<?php } ?> Add News

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

   <?php echo $this->escape($this->news['title']); ?>    <?php echo $this->escape($this->news['title']); ?>  

<?php echo $this->escape($this->news['content']); ?>

Comments <?php foreach ($this->comments as $comment) { ?>

<?php echo $this->escape($comment['name']); ?> writes:

<?php echo $this->escape($comment['comment']); ?>
<?php } ?> Add a Comment

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

 News Admin 

Tip: to keep the form simple, the password is used as the authentication mechanism.

To use the template, you only need to replace the comments with several lines of code. For example, IndexController. php becomes the following:

<?phpclass 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 clear, the entire business logic of the home page of this program has only four lines of code. AddController. php is more complex and requires more code:

<?phpclass 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, this controller does not need a view.

In AdminController. php, you need to process two actions: Display management interface and approval news:

<?phpclass 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 'The password is incorrect.';    }  }  function __call($action, $arguments)  {    $this->_redirect('/');  }}?>

Finally, ViewController. php:

<?phpclass 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 simple, we provide a fully functional News and Comment program. The best thing is that with a good design, adding features becomes simple. As Zend Framework becomes more mature, it will only become better.

More information

This tutorial only discusses some features on the surface of ZF, but there are also some other resources for reference. At http://framework.zend.com/manual/you can obtain a manual query. Rob Allen introduced some experience in using Zend Framework at http://akrabat.com/zend-framework/while Richard Thomas was also in workshop. If you have your own ideas, visit the new Zend Framework Forum: http://www.phparch.com/discuss/index.php/f/289 //.

Conclusion

It is easy to evaluate the preview version. I also encountered many difficulties when writing this tutorial. In general, I think Zend Framework shows the promise that everyone who joins the Framework wants to continue to improve it.

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.