


Detailed explanation of Zend Framework smarty usage examples, zendsmarty_PHP tutorial
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
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: :
<?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(); ?>
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');
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');
The setting throws an exception, but after the server is actually working, 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'; /** * 对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);
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:
<?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('views'); } function indexAction() { //定义模版显示的变量 $data[`title′]=〞hello world〞; //传递变量到模版 $this->views->assign($data); //显示模版 $this->views->display('index/index.tpl'); } 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,中文意思就是可扩展标记语言,标记语言就是那种用尖括号(<>)括来括去的那种语言,比如说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'); } }
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['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 ))); ?>
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

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

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)

Hot Topics



.NET Framework 4 is required by developers and end users to run the latest versions of applications on Windows. However, while downloading and installing .NET Framework 4, many users complained that the installer stopped midway, displaying the following error message - " .NET Framework 4 has not been installed because Download failed with error code 0x800c0006 ". If you are also experiencing it while installing .NETFramework4 on your device then you are at the right place

Whenever your Windows 11 or Windows 10 PC has an upgrade or update issue, you will usually see an error code indicating the actual reason behind the failure. However, sometimes confusion can arise when an upgrade or update fails without an error code being displayed. With handy error codes, you know exactly where the problem is so you can try to fix it. But since no error code appears, it becomes challenging to identify the issue and resolve it. This will take up a lot of your time to simply find out the reason behind the error. In this case, you can try using a dedicated tool called SetupDiag provided by Microsoft that helps you easily identify the real reason behind the error.
![SCNotification has stopped working [5 steps to fix it]](https://img.php.cn/upload/article/000/887/227/168433050522031.png?x-oss-process=image/resize,m_fill,h_207,w_330)
As a Windows user, you are likely to encounter SCNotification has stopped working error every time you start your computer. SCNotification.exe is a Microsoft system notification file that crashes every time you start your PC due to permission errors and network failures. This error is also known by its problematic event name. So you might not see this as SCNotification having stopped working, but as bug clr20r3. In this article, we will explore all the steps you need to take to fix SCNotification has stopped working so that it doesn’t bother you again. What is SCNotification.e

Microsoft Windows users who have installed Microsoft.NET version 4.5.2, 4.6, or 4.6.1 must install a newer version of the Microsoft Framework if they want Microsoft to support the framework through future product updates. According to Microsoft, all three frameworks will cease support on April 26, 2022. After the support date ends, the product will not receive "security fixes or technical support." Most home devices are kept up to date through Windows updates. These devices already have newer versions of frameworks installed, such as .NET Framework 4.8. Devices that are not updating automatically may

It's been a week since we talked about the new safe mode bug affecting users who installed KB5012643 for Windows 11. This pesky issue didn't appear on the list of known issues Microsoft posted on launch day, thus catching everyone by surprise. Well, just when you thought things couldn't get any worse, Microsoft drops another bomb for users who have installed this cumulative update. Windows 11 Build 22000.652 causes more problems So the tech company is warning Windows 11 users that they may experience problems launching and using some .NET Framework 3.5 applications. Sound familiar? But please don't be surprised

PHP implementation framework: ZendFramework introductory tutorial ZendFramework is an open source website framework developed by PHP and is currently maintained by ZendTechnologies. ZendFramework adopts the MVC design pattern and provides a series of reusable code libraries to serve the implementation of Web2.0 applications and Web Serve. ZendFramework is very popular and respected by PHP developers and has a wide range of

How to use ACL (AccessControlList) for permission control in Zend Framework Introduction: In a web application, permission control is a crucial function. It ensures that users can only access the pages and features they are authorized to access and prevents unauthorized access. The Zend framework provides a convenient way to implement permission control, using the ACL (AccessControlList) component. This article will introduce how to use ACL in Zend Framework

According to news on December 9, Cooler Master recently demonstrated a mini chassis kit in cooperation with notebook modular solution provider Framework at a demonstration event at the Taipei Compute Show. The unique thing about this kit is that it can be compatible with and Install the motherboard from the framework notebook. Currently, this product has begun to be sold on the market, priced at 39 US dollars, which is equivalent to approximately 279 yuan at the current exchange rate. The model number of this chassis kit is named "frameWORKMAINBOARDCASE". In terms of design, it embodies the ultimate compactness and practicality, measuring only 297x133x15 mm. Its original design is to be able to seamlessly connect to framework notebooks
