Zend Framework + smarty usage examples, zendsmarty
This example describes how to use Zend Framework + smarty. We will share this with you for your reference. The details are as follows:
I. 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:
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 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 content of index. php is as follows ::
<? Php // error prompt: error_reporting (E_ALL | E_STRICT); // set the time zone date_default_timezone_set ('Asia/Shanghai'); // specify the path to the referenced file: set_include_path ('. '. PATH_SEPARATOR. '. /library /'. PATH_SEPARATOR. '. /webapp/models /'. PATH_SEPARATOR. get_include_path (); // The Loader must be manually loaded. phpinclude "Zend/Loader. php "; // automatically load the class. during use, function _ autoload ($ class) {Zend_Loader: loadClass ($ class);} // getInstance () is directly instantiated () method to obtain the frontend 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); // sets the base address to facilitate later url jump to users ,. note: It is case sensitive! $ FrontController-> setBaseUrl ('/test'); // to use the smarty template, you must disable the view assistant. $ frontController-> setParam ('noviewrenderer', true); // closes the error message. When a request error occurs, go to ErrorController's errorAction controller // $ frontController-> throwExceptions (false .. 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_dynam Ic ($ param, $ content, & $ views) {return $ content;} $ views-> register_block ('dynamic ', 'smarty _ block_dynamic', false); Zend_Registry :: set ('view', $ views); // start to run 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:
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.
$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.
$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. :
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:
<?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:
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. :
Class IndexController extends Zend_Controller_Action {var $ views;/* template object */var $ data;/* object for passing template variables */function init () {// retrieve the registered object $ this-> views = Zend_Registry: get ('view');} function indexAction () {// defines the variable $ data [comment title '] = "hello world" displayed in the template; // transmits 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, which is located in test/webapp/templates/index. tpl:
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 Path: test/webapp/controller/IndexController. php:
Class IndexController extends Zend_Controller_Action {var $ views;/* template object */var $ data;/* object for passing 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 (that is, the result returned by the server) of the response ), $ retval-> value ()-> scalarval (); the PHP variable $ sum = $ retval-> value ()-> scalarval ();} that describes the response result is returned ();}} @ $ data ['var1'] = $ _ POST ['var1']; @ $ data ['var2'] = $ _ POST ['var2']; @ $ data ['sum'] = $ sum; @ $ data [your action '] = "$ this-> baseurl/index /"; // construct the complete url to the template $ time = date ("Y-m-d H: I: s ") @ $ data ['url'] = "$ this-> baseurl/index/add/id/$ sum/time/$ time "; /pass the variable to the template $ this-> views-> assign ($ data); // display the template $ this-> views-> display ('index/index. tpl ');} function addAction () {$ data ['title'] = "experiment "; // get 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:
Hello, the following example shows how to use Xmlrpc to call a remote server method! And we will pass the result to another function!
Code:
{If $ sum}: click here! {/If}
Location: test/webapp/templates/index/add. tpl:
Now it's {$ time} {$ title}. What you just passed is {$ id}
3) create an XMLRPC server program
Location: web/1.php:
<? 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; // returns 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 ", "signatur E "=> $ 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!