This article describes the relevant knowledge points for getting started with Zend Framework development. Share to everyone for your reference, as follows:
The Zend framework is released! While still in the early stages of development, this tutorial highlights some of the best features of the present and guides you through the construction of a simple program.
Zend first released ZF in the community. Based on the same idea, this tutorial is written to showcase the existing features of ZF. As this tutorial is published online, I will update it when ZF changes to be as effective as possible.
Requirements
The Zend framework requires PHP5. To make better use of the code in this tutorial, you will also need an Apache Web server. Because the demonstration program (a news management system) used the mod_rewrite.
The code for this tutorial is free to download, so you can try it yourself. You can download it from the Brain Buld website to the code: http://brainbulb.com/zend-framework-tutorial.tar.gz.
Download ZF
When you start this tutorial, you need to download the latest version of ZF. You can download the tar.gz or zip file manually from Http://framework.zend.com/download by using the browser, 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 its own pear channel for simplified downloads.
Once you have downloaded the preview version, put the library directory in a convenient place. In this tutorial, I renamed the Library to Lib in order to have a concise directory structure:
app/
views/
controllers/
www/
. htaccess
index.php
lib/
The WWW directory is the document root directory, the controllers and views directory is an empty directory that will 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 the foundation for the programs you develop, and in part determines that the Zend framework is not just a collection of components. However, you need to put all the requests you get into a simple PHP script before you use them. This tutorial uses the 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 document root directory and add the following:
Rewriteengine Onrewriterule!/. (JS|ICO|GIF|JPG|PNG|CSS) $ index.php
Tip: A TODO project in Zend_controller is to remove the dependency on mod_rewrite. In order to provide a preview version of the example, this tutorial uses mod_rewrite.
If you add the 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 specific 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 will also set the path of the ZF Library to Include_path. You can set it on php.ini or simply put the following in your. htaccess file:
Php_value include_path "/path/to/lib"
Zend
The Zend class contains a collection of frequently used static methods. Here's the only class you want to add manually:
<?phpinclude ' zend.php ';? >
Once you have included the zend.php, you have included all the class methods of the Zend class. Use LoadClass () to simply load other classes. For example, load the Zend_controller_front class:
<?phpinclude ' zend.php '; Zend::loadclass (' Zend_controller_front ');? >
Include_path can understand LoadClass () and ZF's organization and directory structure. I use it to load all other classes.
Zend_controller
This controller is very intuitive to use. In fact, I didn't use its rich documentation when I wrote the tutorial.
Hint: The document is now visible in http://framework.zend.com/manual/zend.controller.html.
I started with a front Controller called Zend_controller_front. In order to understand how it works, please 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 chaining, you can 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 visit/foo/bar, there will be an error. That's right! It lets you know what's going on. The main problem is that you cannot find the indexcontroller.php file.
Before you create this file, you should first understand how ZF wants you to organize these things. ZF splits the request for access. If the access is/foo/bar, Foo is the controller, and bar is the action. Their default values are index.
If Foo is CONTROLLER,ZF you will find the foocontroller.php file in the Controllers directory. Since this file does not exist, ZF returns to indexcontroller.php. The results are not found, the error.
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 stated earlier, the Indexcontroller class handles requests from the index controller or controller that do not exist. The Indexaction () method handles access to the action as 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.) Accessing any other resource will only result in an error.
Before you continue, add another useful class method to the Indexcontroller. Whenever you access a nonexistent controller, call the Norouteaction () class method. For example, if foocontroller.php does not exist, access to/foo/bar executes Norouteaction (). But access to/index/foo still goes wrong, because Foo is an action, not a 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 ('/'); }}? >
The example uses $this->_redirect ('/') to describe the behavior that may occur when executing norouteaction (). This redirects access to the root document (home page) for non-existent controllers.
Now create the 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 visit/foo/bar again, you will find that baraction () is executed because bar is the action. Now you're not just supporting a friendly URL, you can do it in just a few lines of code. Cool it!
You can also create a __call () class method to handle an undefined action 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 have just a few lines of code to handle the user's visit well, ready to continue.
Zend_view
Zend_view is a class to help you organize your view logic. This is not known to the template-system, and for the sake of simplicity, this tutorial does not use templates. If you like, you might as well use it.
Remember, all access is now handled by the front controller. So the application framework already exists, and it must be adhered to in addition. In order to demonstrate a basic application of Zend_view, the indexcontroller.php is modified 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 was an Example This was an example.
Now, if you visit the root resource of your website, you will see the content of example.php. It's not going to work, but you need to be aware that you're developing Web applications in a very clear way in a structured and organized manner.
To make Zend_view's application clearer, modify your template (example.php) to include the following:
<?php echo $this->escape ($this->title);?> <?php echo $this->escape ($this->body);?>
Two features have been added now. The $this->escape () class method is used for all outputs. Even if you create the output yourself, just like this example. Avoiding all 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 show Dynamic Data. These can also be defined in the controller, so we modify the 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 that you are accessing the root directory again, you should be able to see the values used by the template. Because the $this you use in the template is the instance executed within the Zend_view scope.
Remember that example.php is just a normal PHP script, so you can do exactly what you want to do. Just try to use the template only when you want the data to be displayed. Your controller (the module the controller distributes) should handle all of your business logic.
Before I go on, I want to make the last hint about Zend_view. Initializing the $view object within each of the Controller's class methods requires additional input, and our primary goal is to make it easier to quickly develop a Web application. If all templates are placed in one directory, it is also controversial whether to call Setscriptpath () in each example.
Fortunately, the Zend class contains a register to help reduce the workload. You can use the register () method to store your $view object in a register:
<?phpzend::register (' View ', $view);? >
Search using the Registry () method:
<?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 efficient way to filter input. You can initialize by providing a set of data to be filtered.
<?php$filterpost = new Zend_inputfilter ($_post);? >
This will set ($_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 the data. Therefore, when you manipulate the input data, you should always use Zend_inputfilter.
Tip: Zend_filter provides the same static method as the Zend_inputfilter method.
Construction of news management system
Although the preview provides many components (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 ZF's basic structure and design.
Everyone develops programs that are different, and the Zend Framework tries to accommodate these differences. Again, this tutorial is written according to my preference, please adjust it according to your preference.
When I develop the program, I will do the interface first. This does not mean that I spend all my time on labels, stylesheets and pictures, but I think of them from the perspective of a user. So I think of the program as a collection of pages, and each page is a separate URL. This news system is made up of the following URLs:
/
/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 handles some management such as approving news, Viewcontroller specific news and corresponding comments.
If your foocontroller.php is still there, remove it. Modify indexcontroller.php for the business logic to add the appropriate action and some comments:
<?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 Addcontroller's Indexaction () method cannot be called. This class method is executed when/add is accessed. Because users can access this URL manually, it is possible, so you have to redirect users to the homepage, display errors or actions that you think are 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 the others, because you don't know what's the effective action. 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 made a little simpler. I used a simple class that uses SQLite to store and query news items 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); 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->_db->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->_db->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->_db->query ($sql)) {return $result->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 APPR Oval = ' 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->fetch All (); } else {return $result->fetch (); }} return FALSE; }}?>
(You can easily replace this class with your own solution.) Here is just a complete example of the introduction, not recommended to implement this. )
The constructor for this class requires the full path and file name of the SQLite database, which you must create 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 it once, and then give the full path and file name of the database class constructor directly:
<?php$db = new Database ('/path/to/db.sqlite ');? >
Integration
For consolidation, create Database.php,loadclass () in the Lib directory to find it. Your index.php file will now initialize the $view and $db and store it in the register. You can also create the __autoload () function to automatically load the classes you need:
<?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:
NewsNews
Escape ($entry [' id ']),?> "> <?php echo $this->escape ($entry [' title ']);?>
ADD News
The view.php template can be used to display selected news items:
Comments
<?php echo $this->escape ($comment [' comment ']);?>
Add a Comment
Finally, the admin.php template can be used to approve news items:
News Admin
Tip: To keep it simple, this table is a password-only authentication mechanism.
Where you use the template, you just need to replace the comment with a few lines of code. As indexcontroller.php, it 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 more clear, the entire business logic of this program's home page is only four lines of code. Addcontroller.php is a little more complicated, it needs 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, the controller does not need a view.
In admincontroller.php, you have to handle the display management interface and approve the news two action:
<?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, the 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 it is simple, we provide a more functional news and review program. The best place is because of the better design, the added 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 some other resources available for reference. In http://framework.zend.com/manual/there is a manual that can be queried, Rob Allen introduced some of his experience using the Zend Framework in http://akrabat.com/zend-framework/, Richard Thomas also provided some useful notes in http://www.cyberlot.net/zendframenotes. If you have your own ideas, you can visit the Zend Framework's new forum: http://www.phparch.com/discuss/index.php/f/289//.
Conclusion
It is easy to evaluate the preview, and I have a lot of difficulties in writing this tutorial. Overall, I think the Zend Framework shows promise that everyone who joins is trying to improve it.
More interested in Zend related content readers can view the topic: "Zend framework of the introductory tutorial", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Tutorial", "PHP object-oriented Programming introduction tutorial "," Introduction to Php+mysql Database Operation "and" PHP common database Operation Skills Summary "
It is hoped that this article will help you to design PHP based on the Zend Framework framework.