Zend Framework + smarty Application

Source: Internet
Author: User
Tags download zend smarty template zend framework
Zend Framework + Smarty Application Example 1. Introduction to Zend Framework
Zend Framework uses the Model-View-Controller (MVC) structure. This is used to separate your program into different parts, making development and maintenance easy.

Run Zend Framework: PHP 5.1.4 (or higher). The Web server supports mod_rewrite. Apache is used in this example. Download Zend framework.zend.com/downloadfrom http://framework.zend.com/download.

Ii. Zend Framework Configuration
1. directory structure
Although Zend Framework does not require a standard directory structure, it still has some common directory structures. This directory structure assumes that you have full control over Apache configuration. (The following example uses a local machine. You need to make changes based on your own situation. The root directory of my server points to the Web Folder)

Reference:

Web/
Test/
/Webapp
/Controllers
/Models
/Templates
/Templates_c
/Library
/Webroot
/Images
/Js
/Css

We have separated the model, view, and controller files 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 you need other library files, you can put them here. In this example, we use the Smarty template technology, so we should also put the Smarty library file under the library file!

2. Start the file
1) Configure. htaccess
We use a single entry file index. php to access our program. This provides the center of all pages in the program and ensures that the runtime environment is correctly configured. We use the. htaccess file to achieve this goal. Add the. htaccess file to the root directory of test. The content is as follows:

Copy content to clipboard

Code:

RewriteEngine on
RewriteRule !".(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 the apache configuration file httpd. conf.
1. Find "# LoadModule rewrite_module modules/mod_rewrite.so" and remove the previous!
2. Find "Change AllowOverride None to AllowOverride All" and restart apache.
3. Start the file index. php
Index. php is placed in the root directory of test. The following is the content of index. php: copy the PHP content to the clipboard PHP code:

Copy content to clipboard

Code:

<? Php
// Enable the error message
Error_reporting (E_ALL | E_STRICT );
// Set the time zone
Date_default_timezone_set ('Asia/Shanghai ');
// Specify the path of the referenced File
Set_include_path ('.'.
Path_separator. './library /'.
Path_separator. './webapp/models /'.
Path_separator. get_include_path ());
// You must manually load loader. php
Include "Zend/loader. php ";
// Automatically load the class. It is directly instantiated for use.
Function _ autoload ($ class ){
Zend_loader: loadclass ($ class );
}
// The getinstance () method is used to obtain the front-end controller instance.
$ Frontcontroller = zend_controller_front: getinstance ();
// Set the working directory of the front-end router
$ Frontcontroller-> setcontrollerdirectory (Array ("default" => './webapp/controllers '));
// Throw an exception
$ Frontcontroller-> throwexceptions (true );
// Set the base address to facilitate later URL jump users. Note that it is case sensitive!
$ Frontcontroller-> setbaseurl ('/test ');
// Use the smarty template to disable its own view assistant.
$ Frontcontroller-> setparam ('noviewrenderer', true );
// Disable the error message. When a request error occurs, go to the errorAction controller of ErrorController.
// $ FrontController-> throwExceptions (false );
// Yes .. Register
Zend_Registry: set ('font', $ frontController );
// ------------ Configure the Smarty template ----------------
Include 'smarty/Smarty. class. php ';
/**
* Initialize 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 );
Zend_registry: Set ('Views ', $ views );
// Start running the program
$ Frontcontroller-> dispatch ();
?>

4) Startup File description
Zend Framework is designed in this way. All files must be included in include_path. We also include our model directory in the include path so that we can easily load our model classes in the future. At the beginning, we must include Zend/Loader. php so that we can access the Zend_Loader class. There is a static method in the Zend_Loader class so that we can load other Zend Framework classes, for example:

Copy content to clipboard

Code:

Zend_Loader::loadClass('Zend_Controller_Front');

Zend_Loader: loadClass loads named classes. It converts the underline into a path separator and adds the. php suffix at the end. In this way, the class Zend_Controller_Front will be loaded from Zend/Controller/font. php. If you use the same naming rules in your class library, you can use Zend_Loader: loadCass () to load them. We need to load the Controller class and the routing class.
The front-end controller uses the routing class to map the request URL to the correct PHP function, and then displays the page. To make routing work, we need to solve which part of the URL is directed to the index. php path, so that it can find the url element after that point.
We need to configure the front-end router so that it can find out the controller from which directory.

Copy content to clipboard

Code:

$frontController = Zend_Controller_Front::getInstance();
$frontController->setControllerDirectory('./application/controllers');

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

Copy content to clipboard

Code:

$frontController->throwExceptions(true);

In this example, we use the Smarty template technology. Therefore, we disable the view that comes with ZF. $ FrontController-> setParam ('noviewrenderer', true); set the base address to facilitate url redirection later. $ FrontController-> setBaseUrl ('/test'); Zend_Registry: set ('font', $ frontController); next, set the Smarty. First, we reference the class Smarty. class. php In the class library. And set its path so that ZF can know its location. Copy the PHP content to the clipboard. PHP code:

Copy content to clipboard

Code:

Include 'smarty/smarty. Class. php ';
/**
* Initialize 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 to store $ view, so that we can call it to operate on any other party of the program. Zend_Registry: set ('Views ', $ views); after setting, run the program. $ FrontController-> dispatch ();
At this time, if you run http: // 127.0.0.1/test for testing. There will be an error similar to Fatal error: Uncaught exception 'zend _ Controller_Dispatcher_Exception 'with message 'invalid controller specified (index)' in... This is because we have not set our program.

3. Set the program
Before setting files, it is important to understand how Zend Framework organizes pages. The page of each application is called action, and many actions constitute a controller. For example, for URL http: // localhost/test/news/view/id/1 in this format, the controller is news, the action is view, and the following IDs and 1 are, they are the parameters and values passed to this actionView.

The Zend Framework controller regards index as a default action and retains it as a special action. In this way, the index action in the news controller is executed for URLs such as http: // localhost/test/news. 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. Set the Controller
Now you can set the controller. In Zend Framework, a Controller is a class that must be called {Controller name} Controller. Note that {Controller name} must start with an uppercase letter. In addition, this class must be in a file such as {Controller name} Controller. php. This file must also be in a specific Controller directory. Note that {Controller name} must start with an uppercase letter and other letters must be in lowercase. Each action is a public function in the Controller class. The name must be {action name} Action. Here, {action name} should start with a lowercase letter. In this way, in the file test/webapp/controllers/IndexController. php, our controller class is called IndexController. Location: test/webapp/controllers/IndexController. php: copy the PHP content to the clipboard. PHP code:

Copy content to clipboard

Code:

<?php
class IndexController extends Zend_Controller_Action
{
function init()
{
}
function indexAction()
{
}
function addAction()
{
}
}
?>

We now have three actions we want to use, which will not work until we have set the view. Function init is a special function. In short, it is a function called when constructing a function in the controller.
The URL of each action is as follows:

Copy content to clipboard

Code:

http://localhost/test/ in IndexController::indexAction()
http://localhost/test/index/add in IndexController::addAction()

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

5. Set the view
Because this instance uses the Smarty template, it is slightly different from the View of ZF! Next I will directly introduce any usage of Smarty in ZF. Before using Smarty, we should first retrieve the $ view defined in index. php and define the variables to be displayed in the template. Copy the PHP content to the clipboard. PHP code:

Copy content to clipboard

Code:

Class indexcontroller extends zend_controller_action
{
VaR $ views;/* template object */
Var $ data;/* objects that pass template variables */
Function init ()
{
// Retrieve the registered object
$ This-> views = Zend_Registry: get ('view ');
}
Function indexAction ()
{
// Define the variables displayed in the template
$ Data [comment title '] = "hello world 〞;
// Pass the variable to the template
$ This-> views-> assign ($ data );
// Display template
$ This-> views-> display ('index/index. tpl ');
}
Function addAction ()
{
}
}

Next, we will start to create a View File where the PHP content is copied to the clipboard by test/webapp/templates/index. tpl:

Copy content to clipboard

Code:

{$title}

Enter http: // 127.0.0.1/test. "Hello world" should appear.
In this way, a simple instance is complete. Next we will use XMLRPC technology to implement a slightly more complex instance!

Iii. XMLRPC
1. What is XMLRPC?
XMLRPC, as its name implies, is an RPC that uses XML technology. So what are XML and RPC?
RPC is short for Remote Procedure Call. It is a remote process call technique that calls a process (method) on a local machine, this process is also known as "distributed computing, a technology invented to improve the interoperability of separate machines.
XML is also an abbreviation of RPC, Which is extensible markup language. The Chinese meaning is extensible markup language, and the markup language is the kind of angle brackets (<>) include the language to be included, such as HTML. The scalability of XML is also reflected in that it only defines the language format, and does not define too many keywords, that is, tags ), therefore, you can select the custom tag as needed. This free and simple syntax rule also makes it widely used to represent various types of data.

2. Use XMLRPC in ZF
1) Create indexcontroller. php
Next we will complete an instance. For convenience, we will not create a new controller. Just modify the indexcontroller we just created and you will be able to use it! In addition, we also need to establish an XMLRPC server program. It is located in the root directory of the Web server (in the local machine, that is, in the parent directory of the test file, named 1.php). Because XMLRPC uses the class library, we also need to download libphpxmlrpc and put it in the library folder!
File Location: Test/webapp/controller/indexcontroller. php copy the PHP content to the clipboard PHP code:

Copy content to clipboard

Code:

Class IndexController extends Zend_Controller_Action
{
Var $ views;/* template object */
Var $ data;/* objects that pass template variables */
Public function init ()
{
// Retrieve the registered object
$ This-> views = Zend_Registry: get ('view ');
$ This-> font = zend_registry: Get ('font ');
// Obtain the base address
$ This-> baseurl = $ this-> font-> getbaseurl ();
}
Function indexaction ()
{

@ Include "libphpxmlrpc/XMLRPC. Inc ";
@ Include "libphpxmlrpc/xmlrpcs. Inc ";
If (isset ($ _ post ['var1']) & isset ($ _ post ['var2'])
{
// Create a 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 ("Reason:". htmlspecialchars ($ retval-> faultstring ()));
}
Else
{
// $ Retval-> value () gets the xmlrpcval (the result returned by the server) of the response ),
$ Retval-> value ()-> scalarval (); get the PHP variable that describes the response result
$ Sum = $ retval-> value ()-> scalarval ();
}
}

@ $ Data ['var1'] = $ _ post ['var1'];
@ $ Data ['var2'] = $ _ post ['var2'];
@ $ Data ['sum'] = $ sum;
@ $ Data [Export action '] = "$ this-> baseurl/index /";
// Construct a complete URL for the Template
$ Time = date ("Y-m-d h: I: s ")
@ $ Data ['url'] = "$ this-> baseurl/index/Add/ID/$ sum/time/$ time ";
/Pass variables to the template
$ This-> views-> assign ($ data );
// Display template
$ This-> views-> display ('index/index. TPL ');
}

Function addaction ()
{
$ Data ['title'] = "experiment ";
// Obtain the passed Value
$ 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 display template file
Location: Test/webapp/templates/index. TPL copy the PHP content to the clipboard. PHP code:

Hello, the following example shows how to use Xmlrpc to call a remote server method! And we will pass the result to another function!

+

Copy content to clipboard

Code:

{If $ sum}
Click to have a look!
{/If}

Location: test/webapp/templates/index/add. tpl copy the PHP content to the clipboard. PHP code:

Now is {$ time}

{$ Title} What you just passed is {$ id}

3) create an XMLRPC server program
Location: copy the php content to the clipboard in web/1. PHP:

Copy content to clipboard

Code:

<? Php
@ Include ("libphpxmlrpc/xmlrpc. inc ");
@ Include ("libphpxmlrpc/xmlrpcs. inc ");
If ($ _ SERVER ['request _ method']! = 'Post ')
{
Exit (0 );
}
$ Add_sig = array ($ xmlrpcString, $ xmlrpcInt, $ xmlrpcInt ));
$ Add_doc = "Add the two integer together ";
Function add ($ params)
{
// Introduce the user error code value
Global $ xmlrpcerruser;
// Return a PHP Array
$ Val = php_xmlrpc_decode ($ params );
$ Ret = $ val [0] + $ val [1];
Return new xmlrpcresp (new xmlrpcval ($ ret, "int "));
}
// Create an xmlrpc_server instance:
$ Server = new xmlrpc_server (array (
"Add" => array (
"Function" => "add ",
"Signature" => $ add_sig,
"Docstring" => $ add_doc
)));
?>

OK. Now open http; // 127.0.0.1/test. The XMLRPC created just now should have been set up. Enter a number and test 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.