_php Example of Zend framework+smarty usage examples

Source: Internet
Author: User

The examples in this article describe the use of Zend Framework+smarty. Share to everyone for your reference, specific as follows:

Introduction of Zend Framework

The Zend framework uses the 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 features, this example uses Apache. From here http://framework.zend.com/download download the Zend Framework, there are two formats. zip or. tar.gz.

Ii. configuration of the Zend framework

1, directory structure

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

Reference:

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

We have separated the files from the models, views, and controllers 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 use the Smarty template technology, so Smarty library files We should also put 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 a central point for all the pages in the program and ensures that the running environment is properly configured. We use the. htaccess file to do this, add the. htaccess file in the root directory of test, which reads as follows:

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

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

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

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

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

<?php//Open error prompts error_reporting (e_all| 
E_STRICT); 
Set time zone Date_default_timezone_set (' Asia/shanghai ');
Indicates the path to the referencing file Set_include_path ('. '). Path_separator.
'./library/'. Path_separator.
'./webapp/models/'. Path_separator.
Get_include_path ()); 
loader.php include "zend/loader.php" must be loaded manually; Automatically load classes, when used, directly instantiate using function __autoload ($class) {zend_loader::loadclass ($class);}//getinstance () method to get the front-end controller instance $ 
Frontcontroller = Zend_controller_front::getinstance (); 
Sets 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 the subsequent URL of the user to jump,. Note that case-sensitive! 
$frontController->setbaseurl ('/test '); 
Use the Smarty template to close its own view assistant. 
$frontController->setparam (' Noviewrenderer ', true);
Turn off the error prompt, and when a request error occurs, go to Errorcontroller's erroraction controller//$frontController->throwexceptions (FALSE); Right..
Register zend_registry::set (' font ', $frontController); ------------Configure Smarty templates----------------include ' smarty/smarty.clAss.php ';
/** * Initializes 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) Description of the startup file

The Zend Framework is designed so that all files must be contained in include_path. We also include our model catalog in include path so that we can easily load our model classes later. In the beginning, we have to include zend/loader.php so that we can access the Zend_loader class, and there are static methods in the Zend_loader class that allow 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 the underline to the path separator and adding the. php suffix at the end. In this way, 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-end controller uses the routing class to map the requested URL to the correct PHP function, and then displays the page. In order for routing to work, it is necessary to resolve which part of the URL is a path to index.php, so that it can look for URL elements after that point.

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

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

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

$frontController->throwexceptions (TRUE);

Because in this example we use the Smarty template technology. So we close the view that ZF itself brings. $frontController->setparam (' Noviewrenderer ', true); Set the base address to make it easier to set the URL later to jump. $frontController->setbaseurl ('/test '); Zend_registry::set (' font ', $frontController); Next, we set up the Smarty. First we refer to the Smarty.class.php class in the class library. And its path is set so that the ZF knows its location. :

Include ' smarty/smarty.class.php '; 
/**
* Initializes 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); When set up, run the program. $frontController->dispatch ();

This time, if you run http://127.0.0.1/test to test. You'll find a bug 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, set up the program

Before you set up a file, it is important to understand how the Zend Framework organizes pages. Each application's page is called an action, and many action components are controllers. For example, for a URL http://localhost/test/news/view/id/1 in such a format, the controller is news, the action is view, and the next ID and 1, respectively, are the parameters and values passed to the Actionview.

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

4, set the controller

You can now set the controller. In the Zend Framework, the controller is a class that must be called {Controller name}controller. Note {Controller name} must begin with an uppercase letter. Also, this class must be in a file called {Controller name}controller.php, which is also required in a specific controller directory. To emphasize, {Controller name} must start with an uppercase 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 Addaction () 
{ 
} 
} 
?>

We now have three of the action we want to use until we set up the view to work. Where function init is a special function, simply put, it is the function that is called when the constructor in 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 for each page in the program.

5, set the view

Since this example uses the Smarty template, the view view of the ZF itself is slightly different from the implementation process. I'll just introduce you to any use of smarty in ZF. Before using smarty, we should first take out the $view defined in index.php and define the variables that need to be shown in the stencil. :

Class Indexcontroller extends Zend_controller_action 
{ 
var $views/* Template Object */
var $data;
function init ()
{
//Take back the registered object
$this->views = zend_registry::get (' views '); 
} 
function indexaction () 
{ 
//defines the variables displayed by the template 
$data [' Title′]="hello world";
//Pass variables to 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, input http://127.0.0.1/test look. There should be "Hello world."

In this way, a simple example is done. Here we combine XMLRPC technology to implement a slightly more complex example!

Third, XMLRPC

1, what is XMLRPC

XMLRPC, as the name suggests, is the application of XML technology RPC. So what is XML and RPC?

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

XML is also an acronym for things like RPC, which is the extensible Markup Language, the Chinese meaning is Extensible Markup language, the markup language is the kind of language, such as HTML, enclosed in angle brackets (<>). The extensibility of XML is also reflected in its definition of only language format, and does not define too many keywords, that is, usually called tags (tag), so users are free to choose the definition tag. Its free and simple grammatical rules also make it widely available to represent a variety of data.

2. Use of XMLRPC in ZF

1) Create indexcontroller.php

Below we will complete an example, for the sake of convenience, does not establish the new controller, the Indexcontroller which we have just established modifies, can use! In addition, we also need to establish a XMLRPC service-side program. Location in the Web server root directory (in this machine, that is, in the test file in the parent directory, named 1.php), because XMLRPC use of 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;///The object passing template variable/public function ini 
T () {//Take back the registered object $this->views = zend_registry::get (' views '); 
$this->font = zend_registry::get (' font ');
The 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.P
HP '); 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 () obtains the answered Xmlrpcval (that is, the result of the server-side return), $retval->value ()->scalarval (), and gets the PHP variable that describes the result of the answer $sum = $retval->value ()->scalarval ();
} @ $data [' var1 ']=$_post[' var1 '];
@ $data [' var2 ']=$_post[' var2 ']; 
@ $data [' Sum ']= $sum; 
@ $data [' action′]= ' $this->baseurl/index/]; 
Constructs a complete URL to the template $time =date ("y-m-d h:i:s") @ $data [' url ']= ' $this->baseurl/index/add/id/$sum/time/$time];
/Transfer variables to the template $this->views->assign ($data); 
Display template $this->views->display (' Index/index.tpl '); 
function Addaction () {$data [' title ']=] "experiment";
The value to be 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 display template file

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

Hello, here is an example of using XMLRPC to invoke a remote server Method! And we pass the results to another function!

Code:

{if $sum}
Click here to see!
{/if}

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

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

3 Create XMLRPC server-side programs

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 two integer together";
function Add ($params)
{
//introduce 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", c22/> "signature" => $add _sig,
"docstring" => $add _doc))
;
? >

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

Related Article

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.

Tags Index: