Home  >  Article  >  php教程  >  Detailed explanation of Zend Framework+smarty usage examples

Detailed explanation of Zend Framework+smarty usage examples

高洛峰
高洛峰Original
2016-12-26 16:01:331110browse

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
//打开错误提示
error_reporting(E_ALL|E_STRICT);
//设定时区
date_default_timezone_set(&#39;Asia/Shanghai&#39;);
//指明引用文件的路径
set_include_path(&#39;.&#39; .
PATH_SEPARATOR . &#39;./library/&#39;.
PATH_SEPARATOR . &#39;./webapp/models/&#39;.
PATH_SEPARATOR . get_include_path());
//必须手动加载Loader.php
include "Zend/Loader.php";
//自动加载类,使用时,直接实例化使用
function __autoload($class){
Zend_Loader::loadClass($class);
}
//getInstance()方法用来获取前端控制器实例
$frontController = Zend_Controller_Front::getInstance();
//设定前端路由器的工作目录
$frontController->setControllerDirectory(array("default"=>&#39;./webapp/controllers&#39;));
//抛出异常
$frontController->throwExceptions(true);
//设置基地址,方便以后url的跳转用户,.注意,区分大小写!
$frontController->setBaseUrl(&#39;/test&#39;);
//使用smarty模版需关闭本身的视图助手.
$frontController->setParam(&#39;noViewRenderer&#39;, true);
// 关闭错误提示,发生请求错误时候,转到ErrorController的errorAction控制器
//$frontController->throwExceptions(false);
//对。。进行注册
Zend_Registry::set(&#39;font&#39;, $frontController);
//------------配置Smarty模版 ----------------
include &#39;Smarty/Smarty.class.php&#39;;
/**
* 对smarty模版进行初始化
**/
$views = new Smarty();
//$views->left_delimiter = "{{";
//$views->right_delimiter = "}}";
$views->compile_dir = &#39;./webapp/templates_c&#39;;
$views->cache_dir = &#39;./webapp/templates_c/cache_c&#39;;
$views->template_dir = "./webapp/templates";
function smarty_block_dynamic($param,$content,&$views)
{
return $content;
}
$views->register_block(&#39;dynamic&#39;,&#39;smarty_block_dynamic&#39;,false);
Zend_Registry::set(&#39;views&#39;, $views);
//开始运行程序
$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. In the Zend_Loader class there are static methods that allow us to load other Zend Framework classes, for example:

Zend_Loader::loadClass(&#39;Zend_Controller_Front&#39;);

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 controllers in.

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

The setting throws an exception, but after the server actually works, we should not display the error message 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 &#39;Smarty/Smarty.class.php&#39;;
/**
* 对smarty模版进行初始化
**/
$views = new Smarty();
//$views->left_delimiter = "{{";
//$views->right_delimiter = "}}";
$views->compile_dir = &#39;./webapp/templates_c&#39;;
$views->cache_dir = &#39;./webapp/templates_c/cache_c&#39;;
$views->template_dir = "./webapp/templates";
function smarty_block_dynamic($param,$content,&$views)
{
return $content;
}
$views->register_block(&#39;dynamic&#39;,&#39;smarty_block_dynamic&#39;,false);

Here, we use ZF’s object registry (Registry) to store $view, so that at any other point in 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

在设置文件以前,理解Zend Framework 如何组织页面很重要。每个应用程序的页面叫做 action ,许多 action 组成控制器。例如,对于这样一个格式的 URL http://localhost/test/news/view/id/1 来说,控制器是news, action 是view,后面的id和1,分别是往这个actionView传递的参数和值。

Zend Framework 控制器把 index 作为一个缺省的action 而保留为特别的action。这样,对于http://localhost/test/news/ 这样的url,在news控制器里的 index action将被执行。Zend Framework 也保留了一个缺省的控制器,也叫做index。这样,http://localhost/test/ 将执行 index控制器下的 action index。

4、设置控制器

现在可以设置控制器了。在Zend Framework 里,控制器是一个必需被叫做{Controller name}Controller 的类。注意{Controller name}必需以大写字母开头。并且,这个类必须在叫做{Controller name}Controller.php这样的文件中,这个文件还必需在特定的控制器目录中。强调一下,{Controller name}必需以大写字母开头并其他字母一定是小写。每个action是在控制器类里的public 函数,名字必需是{action name}Action。在这里,{action name}应该以小写字母开头。这样在文件 test/webapp/controllers/IndexController.php 里我们的控制器类叫做 IndexController,位置:test/webapp/controllers/IndexController.php:

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

   

我们现在有三个我们想使用的action,直到我们设置好视图,它们才工作。其中function init是个特殊的函数,简单的说,它就是在controller中的构造函数时调用的函数。

每个action的 URL 如下:

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

现在,我们在程序里有个能工作的路由器和每个页面的 action。

5、设置视图

因为本实例使用的的是Smarty模版,所以和ZF本身的View视图在实现过程中,稍微有点区别!下面我直接介绍在ZF里是任何使用Smarty的。在使用Smarty之前,我们应该先取出在index.php里定义的$view,并且定义好,需要在模版显示的变量。:

class IndexController extends Zend_Controller_Action
{
var $views; /*模板对象*/
var $data; /*传递模版变量的对象*/
function init()
{
//拿回注册过的对象
$this->views = Zend_Registry::get(&#39;views&#39;);
}
function indexAction()
{
//定义模版显示的变量
$data[`title′]=〞hello world〞;
//传递变量到模版
$this->views->assign($data);
//显示模版
$this->views->display(&#39;index/index.tpl&#39;);
}
function addAction()
{
}
}

   

下面我们开始做视图文件,它们的位置是test/webapp/templates/index/index.tpl:

代码:

{$title}

   

这个时候,输入http://127.0.0.1/test看看。应该会出现“hello world 了。

这样,一个简单的实例就完成了。下面我们结合Xmlrpc技术来实现一个稍微复杂一点的实例!

三、XMLRPC

1、什么是XMLRPC

XMLRPC,顾名思义,就是应用了XML技术的RPC。那么什么是XML和RPC了?

RPC是Remote Procedure Call的缩写,翻译成中文就是远程过程调用,是一种在本地的机器上调用远端机器上的一个过程(方法)的技术,这个过程也被大家称为“分布式计算 ,是为了提高各个分立机器的“互操作性 而发明出来的技术。

XML和RPC一样也是一个东西的缩写,这个东西就是eXtensible Markup Language,中文意思就是可扩展标记语言,标记语言就是那种用尖括号(a8093152e673feb7aba1828c43532094)括来括去的那种语言,比如说HTML。XML的可扩展性也体现在它只定义了语言的格式,而并没有定义过多的关键字,也就是通常所说的标记(Tag),所以用户可以自由地选择定义标记。它的这种自由和简单的语法规则也使得它广为流传,用来表示各种数据。

2、在ZF中使用XMLRPC

1)创建IndexController.php

下面我们来完成一个实例,为了方便起见,就不建立新的Controller,把刚才我们建立的IndexController修改一下,就能使用了!另外我们还需要建立一个XMLRPC的服务端程序。位置在WEB服务器的根目录上(在本机中,也就是在test文件的上级目录中,取名为1.php),由于XMLRPC使用到了类库,我们还需要下载libphpxmlrpc放在library文件夹下!

文件位置:test/webapp/controller/IndexController.php:

class IndexController extends Zend_Controller_Action
{
var $views; /*模板对象*/
var $data; /*传递模版变量的对象*/
public function init()
{
//拿回注册过的对象
$this->views = Zend_Registry::get(&#39;views&#39;);
$this->font = Zend_Registry::get(&#39;font&#39;);
//得到基地址
$this->baseurl=$this->font->getBaseUrl();
}
function indexAction()
{
@include "libphpxmlrpc/xmlrpc.inc";
@include "libphpxmlrpc/xmlrpcs.inc";
if (isset($_POST[&#39;var1&#39;]) && isset($_POST[&#39;var2&#39;]))
{
//创建客户端
$client = new xmlrpc_client(&#39;http://127.0.0.1/1.php&#39;);
//创建一个实例
@ $msg = new xmlrpcmsg("add", array(
new xmlrpcval($_POST[&#39;var1&#39;], "int"),
new xmlrpcval($_POST[&#39;var2&#39;], "int")));
//发送信息,
$response=$client->send($xmlrpc_message);,服务器返回xmlrpcresp的一个实例
$retval = $client->send($msg);
if ($retval->faultCode())
{
print_r("发生一个错误: ");
print_r("原因: " . htmlspecialchars($retval->faultString()));
}
else
{
//$retval->value()获取应答的xmlrpcval(也就是服务器端返回的结果),
$retval->value()->scalarval();得到描述应答结果的PHP变量
$sum = $retval->value()->scalarval();
}
}
@$data[&#39;var1&#39;]=$_POST[&#39;var1&#39;];
@$data[&#39;var2&#39;]=$_POST[&#39;var2&#39;];
@$data[&#39;sum&#39;]=$sum;
@$data[`action′]= "$this->baseurl/index/";
//构造完整的url给模版
$time=date("Y-m-d H:i:s")
@$data[&#39;url&#39;]="$this->baseurl/index/add/id/$sum/time/$time";
/传递变量到模版
$this->views->assign($data);
//显示模版
$this->views->display(&#39;index/index.tpl&#39;);
}
function addAction()
{
$data[&#39;title&#39;]="实验一下";
//得到传递的值
$id=$this->_request->getParam("id");
$time=$this->_request->getParam("time");
$data[&#39;id&#39;]="$id";
$data[&#39;time&#39;]="$time";
$this->views->assign($data);
$this->views->display(&#39;index/add.tpl&#39;);
}
}

   

2)创建显示模版文件

位置:test/webapp/templates/index/index.tpl:

hello,下面演示的是利用Xmlrpc调用远程服务器方法的实例!并且我们把得到的结果传递到另外的一个函数中去!

代码:

{if $sum}
点一下看看!
{/if}

   

位置: test/webapp/templates/index/add.tpl:

现在是{$time}
{$title}你刚才传递的是 {$id}

   

3)创建XMLRPC服务器端程序

位置:web/1.php:

<?php
@include ("libphpxmlrpc/xmlrpc.inc");
@include ("libphpxmlrpc/xmlrpcs.inc");
if ($_SERVER[&#39;REQUEST_METHOD&#39;] != &#39;POST&#39;)
{
exit(0);
}
$add_sig = array(array($xmlrpcString, $xmlrpcInt, $xmlrpcInt));
$add_doc = "Add the two integer together";
function add($params)
{
//引入用户错误代码值
global $xmlrpcerruser;
//返回一个PHP数组
$val = php_xmlrpc_decode($params);
$ret = $val[0] + $val[1];
return new xmlrpcresp(new xmlrpcval($ret, "int"));
}
//创建一个xmlrpc_server的实例:
$server = new xmlrpc_server(array(
"add" => array(
"function" => "add",
"signature" => $add_sig,
"docstring" => $add_doc
)));
?>

   

OK,现在打开http;//127.0.0.1/test/看看。刚才建立的那个XMLRPC应该已经建立起来了,输入数字,测试一下吧!

希望本文所述对大家基于zend framework框架的PHP程序设计有所帮助。

For more Zend Framework+smarty usage examples and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn