The examples in this article describe the usage of Zend Framework+smarty. Share it with everyone for your reference, as follows:
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 easier.
Running Zend Framework requires: PHP 5.1.4 (or higher), the web server supports the mod_rewrite function, and this example uses Apache. Download Zend Framework from here http://framework.zend.com/download, there are two formats: .zip or .tar.gz.
2. Zend Framework configuration
1. Directory structure
Although 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's configuration. (The following uses this machine as an example. You need to make changes according to your own situation. The root directory of my server points to the Web folder)
Quote:
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 various subdirectories under the webroot directory. The downloaded Zend Framework files are placed in the library directory. If we need other library files, they can be placed here. In this example, we use Smarty template technology, so we should also put the Smarty library file under the library file!
2. Startup file
1) Configuration.htaccess
We use a single entry file index.php to access our program, which provides us with the program central point for all pages in the app and ensure that the running environment is configured correctly. We use .htaccess files to achieve this purpose. Add the .htaccess file in the root directory of test with the following content:
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 and open the apache configuration file httpd.conf.
1. Find the sentence "#LoadModule rewrite_module modules/mod_rewrite.so" and remove the # in front of it!
2. Then find "AllowOverride None and change it to AllowOverride All, restart apache That’s it.
3. The startup file index.php
index.php is placed in the root directory of test. The following is the content of index.php: :
<?php //打開(kāi)錯(cuò)誤提示 error_reporting(E_ALL|E_STRICT); //設(shè)定時(shí)區(qū) date_default_timezone_set('Asia/Shanghai'); //指明引用文件的路徑 set_include_path('.' . PATH_SEPARATOR . './library/'. PATH_SEPARATOR . './webapp/models/'. PATH_SEPARATOR . get_include_path()); //必須手動(dòng)加載Loader.php include "Zend/Loader.php"; //自動(dòng)加載類,使用時(shí),直接實(shí)例化使用 function __autoload($class){ Zend_Loader::loadClass($class); } //getInstance()方法用來(lái)獲取前端控制器實(shí)例 $frontController = Zend_Controller_Front::getInstance(); //設(shè)定前端路由器的工作目錄 $frontController->setControllerDirectory(array("default"=>'./webapp/controllers')); //拋出異常 $frontController->throwExceptions(true); //設(shè)置基地址,方便以后url的跳轉(zhuǎn)用戶,.注意,區(qū)分大小寫(xiě)! $frontController->setBaseUrl('/test'); //使用smarty模版需關(guān)閉本身的視圖助手. $frontController->setParam('noViewRenderer', true); // 關(guān)閉錯(cuò)誤提示,發(fā)生請(qǐng)求錯(cuò)誤時(shí)候,轉(zhuǎn)到ErrorController的errorAction控制器 //$frontController->throwExceptions(false); //對(duì)。。進(jìn)行注冊(cè) Zend_Registry::set('font', $frontController); //------------配置Smarty模版 ---------------- include 'Smarty/Smarty.class.php'; /** * 對(duì)smarty模版進(jìn)行初始化 **/ $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); //開(kāi)始運(yùn)行程序 $frontController->dispatch(); ?>
4) Startup file description
Zend Framework is designed in such a way that all files must be included in include_path. We also include our models directory in the include path so we can easily load our model classes later. First, we have to include Zend/Loader.php so that we have access to the Zend_Loader class. 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 the named class. It is implemented by converting underscores into path separators and adding 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 convention in your class library, you can use Zend_Loader::loadCass() to load them. We need to load the controller class and routing class.
The front controller uses routing classes to map the requested URL to the correct PHP function, and then displays the page. In order for routing to work, it needs to resolve which part of the URL is the path to index.php so that it can look for the url element after that point.
We need to configure the front-end router so that it knows which directory to look for our controller in.
$frontController = Zend_Controller_Front::getInstance(); $frontController->setControllerDirectory('./application/controllers');
Set to throw an exception, but after the server actually works, we should not display error messages to the user.
$frontController->throwExceptions(true);
Because in this example we use Smarty template technology. So we close the view that comes with ZF itself. $frontController->setParam('noViewRenderer', true); Set the base address to facilitate setting the url for jump later. $frontController->setBaseUrl('/test');Zend_Registry::set('font', $frontController);Next, we set up Smarty. First, we referenced the Smarty.class.php class in the class library. And its path is set so that the government knows its location. :
include 'Smarty/Smarty.class.php'; /** * 對(duì)smarty模版進(jìn)行初始化 **/ $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 ZF’s object registry (Registry) to store $view, so that at any other end of the program, We can all call it to perform operations. Zend_Registry::set('views', $views); After setting, run the program. $frontController->dispatch();
At this time, if you run http://127.0.0.1/test to test. You 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 have not set up our program yet.
3. Setting program
在設(shè)置文件以前,理解Zend Framework 如何組織頁(yè)面很重要。每個(gè)應(yīng)用程序的頁(yè)面叫做 action ,許多 action 組成控制器。例如,對(duì)于這樣一個(gè)格式的 URL http://localhost/test/news/view/id/1 來(lái)說(shuō),控制器是news, action 是view,后面的id和1,分別是往這個(gè)actionView傳遞的參數(shù)和值。
Zend Framework 控制器把 index 作為一個(gè)缺省的action 而保留為特別的action。這樣,對(duì)于http://localhost/test/news/ 這樣的url,在news控制器里的 index action將被執(zhí)行。Zend Framework 也保留了一個(gè)缺省的控制器,也叫做index。這樣,http://localhost/test/ 將執(zhí)行 index控制器下的 action index。
4、設(shè)置控制器
現(xiàn)在可以設(shè)置控制器了。在Zend Framework 里,控制器是一個(gè)必需被叫做{Controller name}Controller 的類。注意{Controller name}必需以大寫(xiě)字母開(kāi)頭。并且,這個(gè)類必須在叫做{Controller name}Controller.php這樣的文件中,這個(gè)文件還必需在特定的控制器目錄中。強(qiáng)調(diào)一下,{Controller name}必需以大寫(xiě)字母開(kāi)頭并其他字母一定是小寫(xiě)。每個(gè)action是在控制器類里的public 函數(shù),名字必需是{action name}Action。在這里,{action name}應(yīng)該以小寫(xiě)字母開(kāi)頭。這樣在文件 test/webapp/controllers/IndexController.php 里我們的控制器類叫做 IndexController,位置:test/webapp/controllers/IndexController.php:
<?php class IndexController extends Zend_Controller_Action { function init() { } function indexAction() { } function addAction() { } } ?>
我們現(xiàn)在有三個(gè)我們想使用的action,直到我們?cè)O(shè)置好視圖,它們才工作。其中function init是個(gè)特殊的函數(shù),簡(jiǎn)單的說(shuō),它就是在controller中的構(gòu)造函數(shù)時(shí)調(diào)用的函數(shù)。
每個(gè)action的 URL 如下:
http://localhost/test/ in IndexController::indexAction()
http://localhost/test/index/add in IndexController::addAction()
現(xiàn)在,我們?cè)诔绦蚶镉袀€(gè)能工作的路由器和每個(gè)頁(yè)面的 action。
5、設(shè)置視圖
因?yàn)楸緦?shí)例使用的的是Smarty模版,所以和ZF本身的View視圖在實(shí)現(xiàn)過(guò)程中,稍微有點(diǎn)區(qū)別!下面我直接介紹在ZF里是任何使用Smarty的。在使用Smarty之前,我們應(yīng)該先取出在index.php里定義的$view,并且定義好,需要在模版顯示的變量。:
class IndexController extends Zend_Controller_Action { var $views; /*模板對(duì)象*/ var $data; /*傳遞模版變量的對(duì)象*/ function init() { //拿回注冊(cè)過(guò)的對(duì)象 $this->views = Zend_Registry::get('views'); } function indexAction() { //定義模版顯示的變量 $data[`title′]=〞hello world〞; //傳遞變量到模版 $this->views->assign($data); //顯示模版 $this->views->display('index/index.tpl'); } function addAction() { } }
下面我們開(kāi)始做視圖文件,它們的位置是test/webapp/templates/index/index.tpl:
代碼:
{$title}
這個(gè)時(shí)候,輸入http://127.0.0.1/test看看。應(yīng)該會(huì)出現(xiàn)“hello world 了。
這樣,一個(gè)簡(jiǎn)單的實(shí)例就完成了。下面我們結(jié)合Xmlrpc技術(shù)來(lái)實(shí)現(xiàn)一個(gè)稍微復(fù)雜一點(diǎn)的實(shí)例!
三、XMLRPC
1、什么是XMLRPC
XMLRPC,顧名思義,就是應(yīng)用了XML技術(shù)的RPC。那么什么是XML和RPC了?
RPC是Remote Procedure Call的縮寫(xiě),翻譯成中文就是遠(yuǎn)程過(guò)程調(diào)用,是一種在本地的機(jī)器上調(diào)用遠(yuǎn)端機(jī)器上的一個(gè)過(guò)程(方法)的技術(shù),這個(gè)過(guò)程也被大家稱為“分布式計(jì)算 ,是為了提高各個(gè)分立機(jī)器的“互操作性 而發(fā)明出來(lái)的技術(shù)。
XML和RPC一樣也是一個(gè)東西的縮寫(xiě),這個(gè)東西就是eXtensible Markup Language,中文意思就是可擴(kuò)展標(biāo)記語(yǔ)言,標(biāo)記語(yǔ)言就是那種用尖括號(hào)(<>)括來(lái)括去的那種語(yǔ)言,比如說(shuō)HTML。XML的可擴(kuò)展性也體現(xiàn)在它只定義了語(yǔ)言的格式,而并沒(méi)有定義過(guò)多的關(guān)鍵字,也就是通常所說(shuō)的標(biāo)記(Tag),所以用戶可以自由地選擇定義標(biāo)記。它的這種自由和簡(jiǎn)單的語(yǔ)法規(guī)則也使得它廣為流傳,用來(lái)表示各種數(shù)據(jù)。
2、在ZF中使用XMLRPC
1)創(chuàng)建IndexController.php
下面我們來(lái)完成一個(gè)實(shí)例,為了方便起見(jiàn),就不建立新的Controller,把剛才我們建立的IndexController修改一下,就能使用了!另外我們還需要建立一個(gè)XMLRPC的服務(wù)端程序。位置在WEB服務(wù)器的根目錄上(在本機(jī)中,也就是在test文件的上級(jí)目錄中,取名為1.php),由于XMLRPC使用到了類庫(kù),我們還需要下載libphpxmlrpc放在library文件夾下!
文件位置:test/webapp/controller/IndexController.php:
class IndexController extends Zend_Controller_Action { var $views; /*模板對(duì)象*/ var $data; /*傳遞模版變量的對(duì)象*/ public function init() { //拿回注冊(cè)過(guò)的對(duì)象 $this->views = Zend_Registry::get('views'); $this->font = Zend_Registry::get('font'); //得到基地址 $this->baseurl=$this->font->getBaseUrl(); } function indexAction() { @include "libphpxmlrpc/xmlrpc.inc"; @include "libphpxmlrpc/xmlrpcs.inc"; if (isset($_POST['var1']) && isset($_POST['var2'])) { //創(chuàng)建客戶端 $client = new xmlrpc_client('http://127.0.0.1/1.php'); //創(chuàng)建一個(gè)實(shí)例 @ $msg = new xmlrpcmsg("add", array( new xmlrpcval($_POST['var1'], "int"), new xmlrpcval($_POST['var2'], "int"))); //發(fā)送信息, $response=$client->send($xmlrpc_message);,服務(wù)器返回xmlrpcresp的一個(gè)實(shí)例 $retval = $client->send($msg); if ($retval->faultCode()) { print_r("發(fā)生一個(gè)錯(cuò)誤: "); print_r("原因: " . htmlspecialchars($retval->faultString())); } else { //$retval->value()獲取應(yīng)答的xmlrpcval(也就是服務(wù)器端返回的結(jié)果), $retval->value()->scalarval();得到描述應(yīng)答結(jié)果的PHP變量 $sum = $retval->value()->scalarval(); } } @$data['var1']=$_POST['var1']; @$data['var2']=$_POST['var2']; @$data['sum']=$sum; @$data[`action′]= "$this->baseurl/index/"; //構(gòu)造完整的url給模版 $time=date("Y-m-d H:i:s") @$data['url']="$this->baseurl/index/add/id/$sum/time/$time"; /傳遞變量到模版 $this->views->assign($data); //顯示模版 $this->views->display('index/index.tpl'); } function addAction() { $data['title']="實(shí)驗(yàn)一下"; //得到傳遞的值 $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)創(chuàng)建顯示模版文件
位置:test/webapp/templates/index/index.tpl:
hello,下面演示的是利用Xmlrpc調(diào)用遠(yuǎn)程服務(wù)器方法的實(shí)例!并且我們把得到的結(jié)果傳遞到另外的一個(gè)函數(shù)中去!
代碼:
{if $sum} 點(diǎn)一下看看! {/if}
位置: test/webapp/templates/index/add.tpl:
現(xiàn)在是{$time} {$title}你剛才傳遞的是 {$id}
3)創(chuàng)建XMLRPC服務(wù)器端程序
位置: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) { //引入用戶錯(cuò)誤代碼值 global $xmlrpcerruser; //返回一個(gè)PHP數(shù)組 $val = php_xmlrpc_decode($params); $ret = $val[0] + $val[1]; return new xmlrpcresp(new xmlrpcval($ret, "int")); } //創(chuàng)建一個(gè)xmlrpc_server的實(shí)例: $server = new xmlrpc_server(array( "add" => array( "function" => "add", "signature" => $add_sig, "docstring" => $add_doc ))); ?>
? ?
OK,現(xiàn)在打開(kāi)http;//127.0.0.1/test/看看。剛才建立的那個(gè)XMLRPC應(yīng)該已經(jīng)建立起來(lái)了,輸入數(shù)字,測(cè)試一下吧!
希望本文所述對(duì)大家基于zend framework框架的PHP程序設(shè)計(jì)有所幫助。
For more Zend Framework+smarty usage examples and related articles, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
