Home > Backend Development > PHP Tutorial > Detailed explanation of Zend Framework smarty usage examples, zendsmarty_PHP tutorial

Detailed explanation of Zend Framework smarty usage examples, zendsmarty_PHP tutorial

WBOY
Release: 2016-07-12 08:56:38
Original
796 people have browsed it

Detailed explanation of Zend Framework smarty usage examples, zendsmarty

This article describes the usage of Zend Framework smarty with examples. Share it with everyone for your reference, the details are as follows:

1. Introduction to Zend Framework

Zend Framework uses 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 a central point for all pages in the program and ensures 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

Copy after login

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, and then 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: :

<&#63;php 
//打开错误提示
error_reporting(E_ALL|E_STRICT); 
//设定时区
date_default_timezone_set('Asia/Shanghai'); 
//指明引用文件的路径
set_include_path('.' .
PATH_SEPARATOR . './library/'.
PATH_SEPARATOR . './webapp/models/'.
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"=>'./webapp/controllers')); 
//抛出异常
$frontController->throwExceptions(true); 
//设置基地址,方便以后url的跳转用户,.注意,区分大小写!
$frontController->setBaseUrl('/test'); 
//使用smarty模版需关闭本身的视图助手. 
$frontController->setParam('noViewRenderer', true); 
// 关闭错误提示,发生请求错误时候,转到ErrorController的errorAction控制器
//$frontController->throwExceptions(false);
//对。。进行注册
Zend_Registry::set('font', $frontController);
//------------配置Smarty模版 ----------------
include 'Smarty/Smarty.class.php'; 
/**
* 对smarty模版进行初始化
**/
$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);
//开始运行程序
$frontController->dispatch(); 
&#63;>

Copy after login

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('Zend_Controller_Front');

Copy after login

Zend_Loader::loadClass loads a 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 frontend router so it knows which directory to look for our controllers in.

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

Copy after login

The setting throws an exception, but after the server is actually working, we should not display error messages to the user.

$frontController->throwExceptions(true);

Copy after login

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'; 
/**
* 对smarty模版进行初始化
**/
$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);

Copy after login

Here, we use ZF’s object registry (Registry) to store $view, so that we can call it to perform operations at any other party in 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 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. Setup 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:

<&#63;php 
class IndexController extends Zend_Controller_Action 
{ 
function init()
{
} 
function indexAction() 
{ 
} 
function addAction() 
{ 
} 
} 
&#63;>

Copy after login

我们现在有三个我们想使用的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('views'); 
} 
function indexAction() 
{ 
//定义模版显示的变量 
$data[`title′]=〞hello world〞;
//传递变量到模版
$this->views->assign($data);
//显示模版
$this->views->display('index/index.tpl'); 
} 
function addAction() 
{ 
} 
}

Copy after login

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

代码:

{$title}

Copy after login

这个时候,输入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,中文意思就是可扩展标记语言,标记语言就是那种用尖括号(<>)括来括去的那种语言,比如说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('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'])) 
{ 
//创建客户端
$client = new xmlrpc_client('http://127.0.0.1/1.php');
//创建一个实例
@ $msg = new xmlrpcmsg("add", array(
new xmlrpcval($_POST['var1'], "int"),
new xmlrpcval($_POST['var2'], "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['var1']=$_POST['var1'];
@$data['var2']=$_POST['var2'];
@$data['sum']=$sum; 
@$data[`action′]= "$this->baseurl/index/"; 
//构造完整的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']="实验一下"; 
//得到传递的值 
$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'); 
}
}

Copy after login

2)创建显示模版文件

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

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

代码:

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

Copy after login

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

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

Copy after login

3)创建XMLRPC服务器端程序

位置:web/1.php:

<&#63;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)
{
//引入用户错误代码值
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
)));
&#63;>

Copy after login

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

Readers who are interested in more zend-related content can check out the special topics of this site: "Zend FrameWork Framework Introductory Tutorial", "php Excellent Development Framework Summary", "Yii Framework Introduction and Summary of Common Techniques", "ThinkPHP Introductory Tutorial" , "php object-oriented programming introductory tutorial", "php mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone’s PHP program design based on the zend framework.

Articles you may be interested in:

  • Very easy-to-use Zend Framework paging class
  • Summary of precautions related to Zend Framework custom Helper class
  • Zend Overview of the usage of the Bootstrap class in the Framework tutorial
  • Detailed explanation of the base class Zend_Controller_Action in the Zend Framework tutorial
  • Analysis of how zend Framework automatically loads classes
  • Zend Framework generates verification codes and implements verification Code verification function (with demo source code download)
  • Zend Framework's Zend_Mail implements the verification function of sending emails and solves the problem of garbled headers
  • Zend Framework tutorial's Zend_Form component implements form submission and displays errors Prompt method
  • Zend Framework implements multiple file upload function example
  • Environment configuration for getting started with Zend Framework and the first Hello World example (with demo source code download)
  • Zend Framework Summary of introductory knowledge points
  • Zend Framework basic page layout analysis
  • Detailed explanation of Zend Framework paging class usage

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1111890.htmlTechArticleDetailed explanation of Zend Framework smarty usage examples, zendsmarty This article describes the Zend Framework smarty usage examples. Share it with everyone for your reference, the details are as follows: 1. Introduction to Zend Framework...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template