Zend Framework+smarty Usage Example _php instance

Source: Internet
Author: User
Tags uppercase letter smarty template zend framework
The examples in this paper describe Zend Framework+smarty usage. Share to everyone for your reference, as follows:

I. Introduction to the ZEND framework

The Zend framework uses a model-view-Controller (Model-view-controller (MVC)) structure. This is used to separate your programs into different parts to make development and maintenance easier.

Running the Zend Framework requires: PHP 5.1.4 (or higher), WEB server support mod_rewrite function, this instance uses Apache. From here http://framework.zend.com/download download the Zend Framework, available in two formats. zip or. tar.gz.

Ii. configuration of the Zend framework

1. Directory structure

Although the Zend Framework does not impose a standard directory structure, there are some common directory structures. This directory structure assumes that you have complete control over the configuration of Apache. (The following is a native example, you need to change according to your own situation, my server's root directory is pointing to a Web folder)

Reference:

web/
test/
/webapp
/controllers
/models
/templates
/templates_c
/library
/webroot
/images
/js
/css

We have separated the files of the model, view, and controller in the program into different subdirectories. Supported images, scripts and CSS files are stored in different subdirectories under the Webroot directory. The downloaded Zend Framework file is placed in the library directory. If we still need other library files, we can put them here. In this example, we used the Smarty template technology, so the Smarty library file we should also be placed under the library file!

2. startup file

1) configuration. htaccess

We use a single portal file, index.php, to access our programs, which gives us the central point of all the pages in the program and ensures that the running environment is configured correctly. We use the. htaccess file to do this, add the. htaccess file in the root of test, and the contents are as follows:

Rewriteengine onrewriterule! ". (JS|ICO|GIF|JPG|PNG|CSS) $ index.php

2) Configure Apache
At the same time, we also need to make some settings for Apache to open Apache configuration file httpd.conf.

1, find "#LoadModule rewrite_module modules/mod_rewrite.so This sentence, the front of the # removed!

2, and then find "allowoverride None to allowoverride all, restart Apache."

3. Start File index.php
Index.php is placed in the root of test, the following is the contents of index.php::

<?php//Turn On Error hint error_reporting (e_all| E_STRICT); Set time zone Date_default_timezone_set (' Asia/shanghai '); Indicates the path to the referenced file Set_include_path ('. '). Path_separator. './library/'. Path_separator. './webapp/models/'. Path_separator. Get_include_path ());//must be manually loaded Loader.phpinclude "zend/loader.php"; The auto-load class, when used, is instantiated directly using function __autoload ($class) {zend_loader::loadclass ($class);} The getinstance () method is used to obtain the front Controller instance $frontcontroller = Zend_controller_front::getinstance (); Set the working directory of the front-end router $frontcontroller->setcontrollerdirectory (array ("Default" = "./webapp/controllers ')"); Throws an exception $frontcontroller->throwexceptions (true); Set the base address to facilitate later URL of the jump user,. Note, case sensitive! $frontController->setbaseurl ('/test '); Use the Smarty template to turn off the view helper itself. $frontController->setparam (' Noviewrenderer ', true); Turn off the error prompt, when the request error occurs, go to Errorcontroller's erroraction controller//$frontController->throwexceptions (FALSE); Register zend_registry::set (' font ', $frontController);//------------Configure Smarty template----------------include ' smarty/ Smarty.class.php '; /*** initialization of the Smarty templates **/$views = new Smarty ();//$views->left_delimiter = "{{";//$views->right_delimiter = "}}"; $views->compile_dir = ' ./webapp/templates_c '; $views->cache_dir = './webapp/templates_c/cache_c '; $views->template_dir = "./webapp/ Templates "; function smarty_block_dynamic ($param, $content,& $views) {return $content;} $views->register_block (' Dynamic ', ' smarty_block_dynamic ', false); Zend_registry::set (' views ', $views);//Start Running program $frontcontroller->dispatch ();?>

4) Boot file description

The Zend Framework is designed so that all files must be included in the include_path. We also include our model catalog in include path, so that we can easily load our model classes later. At first, we had to include zend/loader.php so that we could access the Zend_loader class, and there are static methods in the Zend_loader class that enable us to load other Zend Framework classes, for example:

Zend_loader::loadclass (' Zend_controller_front ');

Zend_loader::loadclass loads a class that has already been named. It is implemented by converting an underscore into a path isolator, with a. php suffix appended at the end. This way, the class Zend_controller_front will be loaded from zend/controller/font.php. If you use the same naming conventions in your class library, you can load them with Zend_loader::loadcass (). We need to load the controller class and the routing class.

The front controller uses the routing class to map the requested URL to the correct PHP function, and then displays the page. In order for the routing to work, it is necessary to address which part of the URL is the path to the index.php, so that it can look for the URL element behind that point.

We need to configure the front-end router so that it knows from which directory to find our controller.

$frontController = Zend_controller_front::getinstance (); $frontController->setcontrollerdirectory ('./application/controllers ');

Setting throws an exception, but after the server really works, we should not display an error message to the user.

$frontController->throwexceptions (TRUE);

Because in this example we use the Smarty template technology. So we shut down ZF's own view. $frontController->setparam (' Noviewrenderer ', true); Set the base address, which allows you to set the URL later to jump. $frontController->setbaseurl ('/test '); Zend_registry::set (' font ', $frontController); Next, we set the Smarty. First we refer to the Smarty.class.php class in the class library. And its path is set so that ZF knows where it is. :

Include ' smarty/smarty.class.php '; /*** initialization of the Smarty template **/$views = new Smarty ()//$views->left_delimiter = "{{";//$views->right_delimiter = "}}"; Views->compile_dir = './webapp/templates_c '; $views->cache_dir = './webapp/templates_c/cache_c '; $views Template_dir = "./webapp/templates"; function smarty_block_dynamic ($param, $content,& $views) {return $content;} $ Views->register_block (' Dynamic ', ' smarty_block_dynamic ', false);

Here, we use the ZF Object Registry (Registry) to store the $view, so that we can invoke it to operate on any other side of the program. Zend_registry::set (' views ', $views); After setting up, run the program. $frontController->dispatch ();

This time, if you run http://127.0.0.1/test to test. Will find an error similar to Fatal error:uncaught exception ' zend_controller_dispatcher_exception ' with message ' Invalid Controller Specified (index) ' in ... This is because we haven't set up our program yet.

3. Setup program

Before setting up a file, it is important to understand how the Zend Framework organizes pages. Each application's page is called an action, and many actions compose the controller. For example, for a URL of such a format HTTP://LOCALHOST/TEST/NEWS/VIEW/ID/1, the controller is news, the action is view, the following ID and 1, respectively, the parameters and values passed to this actionview.

The Zend Framework Controller retains index as a default action and remains a special action. Thus, for URLs such as http://localhost/test/news/, the index action in the news controller will be executed. The Zend Framework also retains a default controller, also called index. In this way, http://localhost/test/will execute the action index under the index controller.

4. Setting the Controller

Now you can set up the controller. In the Zend Framework, the controller is a class that must be called the {controller name}controller. Note {Controller name} must start with an uppercase letter. Furthermore, this class must be in a file called {Controller name}controller.php, which is also required to be in a specific controller directory. Emphasize that {Controller name} must start with a capital letter and the other letters must be lowercase. Each action is a public function in the Controller class, and the name must be {action name}action. Here, {action name} should start with a lowercase letter. So in the file test/webapp/controllers/indexcontroller.php our controller class is called Indexcontroller, location: test/webapp/controllers/ indexcontroller.php:

<?php class Indexcontroller extends Zend_controller_action {function init () {} function Indexaction () {} function AddA Ction () {}}?>

We now have three actions we want to use until we set up the view and they work. Where function init is a special function, simply put, it is the function that is called when the constructor in the controller.

The URL for each action is as follows:

Http://localhost/test/in indexcontroller::indexaction ()
Http://localhost/test/index/add in Indexcontroller::addaction ()

Now, we have a working router and an action on each page in the program.

5. Set the View

Because this example uses the Smarty template, and the ZF itself view view in the implementation process, a little bit different! Below I directly introduce in ZF is any use of smarty. Before using smarty, we should first take out the $view defined in the index.php and define the variables that need to be shown in the template. :

Class Indexcontroller extends Zend_controller_action {var $views;/* Template Object */var $data;/* object of passing template variable */function init () {// Take back the registered object $this->views = zend_registry::get (' views '); } function Indexaction () {///define the variables shown in the template $data [' Title′]="hello world";//pass the variable to the template $this->views->assign ($data);// Display template $this->views->display (' Index/index.tpl '); } function Addaction () {}}

Let's start with the view files, where they are test/webapp/templates/index/index.tpl:

Code:

{$title}

This time, enter Http://127.0.0.1/test to see. There should be "Hello World".

In this way, a simple instance is completed. Let's combine XMLRPC technology to achieve a slightly more complex example!

Third, XMLRPC

1. What is Xmlrpc

XMLRPC, as the name implies, is RPC, which uses XML technology. So what is XML and RPC?

RPC is the abbreviation of remote Procedure call, translated into Chinese is a long-distance procedure calls, is a local machine on the remote machine to invoke a process (method) technology, this process is called "distributed computing, to improve the interoperability of each discrete machine" and invented the technology.

XML and RPC is also an abbreviation for something, this is extensible Markup Language, Chinese meaning is Extensible Markup Language, markup language is the kind of angle brackets (<>) to enclose the language, such as HTML. The extensibility of XML is also reflected in that it only defines the format of the language, and does not define too many keywords, which is commonly referred to as tags (tag), so users can freely choose to define the tag. Its freedom and simple grammatical rules also make it widely used to represent various kinds of data.

2. Using XMLRPC in ZF

1) Create indexcontroller.php

Let us complete an example, for the sake of convenience, do not set up a new controller, the Indexcontroller we set up just modified, you can use! In addition, we also need to establish a XMLRPC service-side program. Location in the root directory of the Web server (in this machine, that is, in the test file in the parent directory, named 1.php), because XMLRPC used the class library, we also need to download LIBPHPXMLRPC placed in the Library folder!

File Location: test/webapp/controller/indexcontroller.php:

Class Indexcontroller extends Zend_controller_action {var $views;/* Template Object */var $data;/* object for passing template variable */public function init () {//Take back the registered object $this->views = zend_registry::get (' views '); $this->font = zend_registry::get (' font ');//Get base site $this- >baseurl= $this->font->getbaseurl ();} function Indexaction () {@include "libphpxmlrpc/xmlrpc.inc"; @include "Libphpxmlrpc/xmlrpcs.inc"; if (Isset ($_post[') Var1 ']) && isset ($_post[' var2 ')) {//Create client $client = new Xmlrpc_client (' http://127.0.0.1/1.php ');//Create an instance @ $ msg = new Xmlrpcmsg ("Add", Array (new Xmlrpcval ($_post[' var1 '), "int"), new Xmlrpcval ($_post[' var2 '], "int"));//send information, $ response= $client->send ($xmlrpc _message); The server returns an instance of Xmlrpcresp $retval = $client->send ($msg); if ($retval FaultCode ()) {Print_r ("An error occurred:"); Print_r ("Cause:".) Htmlspecialchars ($retval->faultstring ())); } else {//$retval->value () Gets the xmlrpcval of the answer (that is, the result returned by the server side), $retval->value ()->scalarval (), and the PHP variable that describes the result of the reply $sum = $retval->value ()->scalarval ();}} @ $data[' var1 ']=$_post[' var1 '];@ $data [' var2 ']=$_post[' var2 '];@ $data [' Sum ']= $sum; @ $data [' action′]= ' $this->baseurl/index/"; Constructs the complete URL to template $time =date ("y-m-d h:i:s") @ $data [' url ']= $this->baseurl/index/add/id/$sum/time/$time "; /pass variable to template $this->views->assign ($data);//Display template $this->views->display (' Index/index.tpl '); } function Addaction () {$data [' title ']= "Experiment";//Get the value passed $id = $this->_request->getparam ("id"); $time = $this->_ Request->getparam ("Time"); $data [' id ']= "$id"; $data [' Time ']= $time; $this->views->assign ($data); $this->views->display (' index/ Add.tpl '); }}

2) Create a presentation template file

Location: Test/webapp/templates/index/index.tpl:

Hello, the following is an example of invoking a remote server method using Xmlrpc! And we pass the resulting results to another function!

Code:

{if $sum} click to see! {/if}

Location: Test/webapp/templates/index/add.tpl:

Now {$time} {$title} You just passed {$id}

3) Create a XMLRPC server-side program

Location: web/1.php:

<?php@include ("Libphpxmlrpc/xmlrpc.inc"); @include ("Libphpxmlrpc/xmlrpcs.inc"); if ($_server[' Request_method ') ! = ' POST ') {exit (0);} $add _sig = Array (Array ($xmlrpcString, $xmlrpcInt, $xmlrpcInt)), $add _doc = "Add the" Together "; function Add ($pa Rams) {//introduces user error code value global $xmlrpcerruser;//Returns a PHP array $val = Php_xmlrpc_decode ($params); $ret = $val [0] + $val [1];return New Xmlrpcresp (New Xmlrpcval ($ret, "int"));} Create an instance of Xmlrpc_server: $server = new Xmlrpc_server (Array ("add" = = Array ("function" = "add", "signature" = $ Add_sig, "docstring" = $add _doc));? >

OK, now open http;//127.0.0.1/test/to see. The xmlrpc that you have just established should have been established, enter the numbers, test 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.

  • 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.