Zend Framework实现Zend_View集成Smarty模板系统的方法
本文实例讲述了Zend Framework实现Zend_View集成Smarty模板系统的方法。分享给大家供大家参考,具体如下: Zend_View抽象出了Zend_View_Interface,可以让我们集成不同的视图解决方案,例如可以集成smarty。要在zend中使用其他视图系统作为视图,只要实现Zen
本文实例讲述了Zend Framework实现Zend_View集成Smarty模板系统的方法。分享给大家供大家参考,具体如下:
Zend_View抽象出了Zend_View_Interface,可以让我们集成不同的视图解决方案,例如可以集成smarty。要在zend中使用其他视图系统作为视图,只要实现Zend_View_Interface接口即可。
Zend_View_Interface的接口定义:
<?php /** * Interface class for Zend_View compatible template engine implementations * * @category Zend * @package Zend_View * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Zend_View_Interface { /** * Return the template engine object, if any * * If using a third-party template engine, such as Smarty, patTemplate, * phplib, etc, return the template engine object. Useful for calling * methods on these objects, such as for setting filters, modifiers, etc. * * @return mixed */ public function getEngine(); /** * Set the path to find the view script used by render() * * @param string|array The directory (-ies) to set as the path. Note that * the concrete view implentation may not necessarily support multiple * directories. * @return void */ public function setScriptPath($path); /** * Retrieve all view script paths * * @return array */ public function getScriptPaths(); /** * Set a base path to all view resources * * @param string $path * @param string $classPrefix * @return void */ public function setBasePath($path, $classPrefix = 'Zend_View'); /** * Add an additional path to view resources * * @param string $path * @param string $classPrefix * @return void */ public function addBasePath($path, $classPrefix = 'Zend_View'); /** * Assign a variable to the view * * @param string $key The variable name. * @param mixed $val The variable value. * @return void */ public function __set($key, $val); /** * Allows testing with empty() and isset() to work * * @param string $key * @return boolean */ public function __isset($key); /** * Allows unset() on object properties to work * * @param string $key * @return void */ public function __unset($key); /** * Assign variables to the view script via differing strategies. * * Suggested implementation is to allow setting a specific key to the * specified value, OR passing an array of key => value pairs to set en * masse. * * @see __set() * @param string|array $spec The assignment strategy to use (key or array of key * => value pairs) * @param mixed $value (Optional) If assigning a named variable, use this * as the value. * @return void */ public function assign($spec, $value = null); /** * Clear all assigned variables * * Clears all variables assigned to Zend_View either via {@link assign()} or * property overloading ({@link __get()}/{@link __set()}). * * @return void */ public function clearVars(); /** * Processes a view script and returns the output. * * @param string $name The script name to process. * @return string The script output. */ public function render($name); }
集成Smarty的基本实现如下:
smarty下载地址
http://www.smarty.net/files/Smarty-3.1.7.tar.gz
目录结构
root@coder-671T-M:/www/zf_demo1# tree
.
├── application
│ ├── Bootstrap.php
│ ├── configs
│ │ └── application.ini
│ ├── controllers
│ │ ├── ErrorController.php
│ │ └── IndexController.php
│ ├── models
│ └── views
│ ├── helpers
│ └── scripts
│ ├── error
│ │ └── error.phtml
│ └── index
│ ├── index.phtml
│ └── index.tpl
├── docs
│ └── README.txt
├── library
│ ├── Lq
│ │ └── View
│ │ └── Smarty.php
│ └── smartylib
│ ├── debug.tpl
│ ├── plugins
│ │ ├── ...........................
│ │ └── variablefilter.htmlspecialchars.php
│ ├── SmartyBC.class.php
│ ├── Smarty.class.php
│ └── sysplugins
│ ├── ..........................
│ └── smarty_security.php
├── public
│ └── index.php
├── temp
│ └── smarty
│ └── templates_c
│ └── 73d91bef3fca4e40520a7751bfdfb3e44b05bdbd.file.index.tpl.php
└── tests
├── application
│ └── controllers
│ └── IndexControllerTest.php
├── bootstrap.php
├── library
└── phpunit.xml
24 directories, 134 files
/zf_demo1/library/Lq/View/Smarty.php
<?php require_once 'smartylib/Smarty.class.php'; class Lq_View_Smarty implements Zend_View_Interface { /** * Smarty object * * @var Smarty */ protected $_smarty; /** * Constructor * * @param $tmplPath string * @param $extraParams array * @return void */ public function __construct($tmplPath = null, $extraParams = array()) { $this->_smarty = new Smarty (); if (null !== $tmplPath) { $this->setScriptPath ( $tmplPath ); } foreach ( $extraParams as $key => $value ) { $this->_smarty->$key = $value; } } /** * Return the template engine object * * @return Smarty */ public function getEngine() { return $this->_smarty; } /** * Set the path to the templates * * @param $path string * The directory to set as the path. * @return void */ public function setScriptPath($path) { if (is_readable ( $path )) { $this->_smarty->template_dir = $path; return; } throw new Exception ( 'Invalid path provided' ); } /** * Retrieve the current template directory * * @return string */ public function getScriptPaths() { return array ($this->_smarty->template_dir ); } /** * Alias for setScriptPath * * @param $path string * @param $prefix string * Unused * @return void */ public function setBasePath($path, $prefix = 'Zend_View') { return $this->setScriptPath ( $path ); } /** * Alias for setScriptPath * * @param $path string * @param $prefix string * Unused * @return void */ public function addBasePath($path, $prefix = 'Zend_View') { return $this->setScriptPath ( $path ); } /** * Assign a variable to the template * * @param $key string * The variable name. * @param $val mixed * The variable value. * @return void */ public function __set($key, $val) { $this->_smarty->assign ( $key, $val ); } /** * Retrieve an assigned variable * * @param $key string * The variable name. * @return mixed The variable value. */ public function __get($key) { return $this->_smarty->get_template_vars ( $key ); } /** * Allows testing with empty() and isset() to work * * @param $key string * @return boolean */ public function __isset($key) { return (null !== $this->_smarty->get_template_vars ( $key )); } /** * Allows unset() on object properties to work * * @param $key string * @return void */ public function __unset($key) { $this->_smarty->clear_assign ( $key ); } /** * Assign variables to the template * * Allows setting a specific key to the specified value, OR passing an array * of key => value pairs to set en masse. * * @see __set() * @param $spec string|array * The assignment strategy to use (key or array of key * => value pairs) * @param $value mixed * (Optional) If assigning a named variable, use this * as the value. * @return void */ public function assign($spec, $value = null) { if (is_array ( $spec )) { $this->_smarty->assign ( $spec ); return; } $this->_smarty->assign ( $spec, $value ); } /** * Clear all assigned variables * * Clears all variables assigned to Zend_View either via {@link assign()} or * property overloading ({@link __get()}/{@link __set()}). * * @return void */ public function clearVars() { $this->_smarty->clear_all_assign (); } /** * Processes a template and returns the output. * * @param $name string * The template to process. * @return string The output. */ public function render($name) { ob_start(); echo $this->_smarty->fetch ( $name ); unset($name); } }
/zf_demo1/application/configs/application.ini
[production] includePaths.library = APPLICATION_PATH "/../library" bootstrap.path = APPLICATION_PATH "/Bootstrap.php" bootstrap.class = "Bootstrap" appnamespace = "Application" autoloadernamespaces.lq = "Lq_" pluginpaths.Lq_View_Smarty = "Lq/View/Smarty" resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers" resources.frontController.params.displayExceptions = 1 phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1
/zf_demo1/application/Bootstrap.php
<?php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { /** * Initialize Smarty view */ protected function _initSmarty() { $smarty = new Lq_View_Smarty (); $smarty->setScriptPath('/www/zf_demo1/application/views/scripts'); return $smarty; } }
/zf_demo1/application/controllers/IndexController.php
<?php class IndexController extends Zend_Controller_Action { public function init() { /* * Initialize action controller here */ } public function indexAction() { $this->_helper->getHelper('viewRenderer')->setNoRender(); $this->view = $this->getInvokeArg ( 'bootstrap' )->getResource ( 'smarty' ); $this->view->book = 'Hello World! '; $this->view->author = 'by smarty'; $this->view->render('index/index.tpl'); } }
/zf_demo1/application/views/scripts/index/index.tpl
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> {$book} {$author} </body> </html>
如果需要配置smarty可以打开/zf_demo1/library/smartylib/Smarty.class.php文件进行相应配置例如
/** * Initialize new Smarty object * */ public function __construct() { // selfpointer needed by some other class methods $this->smarty = $this; if (is_callable('mb_internal_encoding')) { mb_internal_encoding(Smarty::$_CHARSET); } $this->start_time = microtime(true); // set default dirs $this->setTemplateDir('/www/zf_demo1/temp/smarty' . DS . 'templates' . DS) ->setCompileDir('/www/zf_demo1/temp/smarty' . DS . 'templates_c' . DS) ->setPluginsDir(SMARTY_PLUGINS_DIR) ->setCacheDir('/www/zf_demo1/temp/smarty' . DS . 'cache' . DS) ->setConfigDir('/www/zf_demo1/temp/smarty' . DS . 'configs' . DS); $this->debug_tpl = 'file:' . dirname(__FILE__) . '/debug.tpl'; if (isset($_SERVER['SCRIPT_NAME'])) { $this->assignGlobal('SCRIPT_NAME', $_SERVER['SCRIPT_NAME']); } }
更多关于zend相关内容感兴趣的读者可查看本站专题:《Zend FrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Huawei 휴대폰에서 이중 WeChat 로그인을 구현하는 방법은 무엇입니까? 소셜 미디어의 등장으로 WeChat은 사람들의 일상 생활에 없어서는 안될 커뮤니케이션 도구 중 하나가 되었습니다. 그러나 많은 사람들이 동일한 휴대폰에서 동시에 여러 WeChat 계정에 로그인하는 문제에 직면할 수 있습니다. Huawei 휴대폰 사용자의 경우 듀얼 WeChat 로그인을 달성하는 것은 어렵지 않습니다. 이 기사에서는 Huawei 휴대폰에서 듀얼 WeChat 로그인을 달성하는 방법을 소개합니다. 우선, 화웨이 휴대폰과 함께 제공되는 EMUI 시스템은 듀얼 애플리케이션 열기라는 매우 편리한 기능을 제공합니다. 앱 듀얼 오픈 기능을 통해 사용자는 동시에

프로그래밍 언어 PHP는 다양한 프로그래밍 논리와 알고리즘을 지원할 수 있는 강력한 웹 개발 도구입니다. 그중 피보나치 수열을 구현하는 것은 일반적이고 고전적인 프로그래밍 문제입니다. 이 기사에서는 PHP 프로그래밍 언어를 사용하여 피보나치 수열을 구현하는 방법을 소개하고 구체적인 코드 예제를 첨부합니다. 피보나치 수열은 다음과 같이 정의되는 수학적 수열입니다. 수열의 첫 번째와 두 번째 요소는 1이고 세 번째 요소부터 시작하여 각 요소의 값은 이전 두 요소의 합과 같습니다. 시퀀스의 처음 몇 가지 요소

Huawei 휴대폰에서 WeChat 복제 기능을 구현하는 방법 소셜 소프트웨어의 인기와 개인 정보 보호 및 보안에 대한 사람들의 강조가 높아지면서 WeChat 복제 기능이 점차 주목을 받고 있습니다. WeChat 복제 기능을 사용하면 사용자가 동일한 휴대폰에서 여러 WeChat 계정에 동시에 로그인할 수 있으므로 관리 및 사용이 더 쉬워집니다. Huawei 휴대폰에서 WeChat 복제 기능을 구현하는 것은 어렵지 않습니다. 다음 단계만 따르면 됩니다. 1단계: 휴대폰 시스템 버전과 WeChat 버전이 요구 사항을 충족하는지 확인하십시오. 먼저 Huawei 휴대폰 시스템 버전과 WeChat 앱이 최신 버전으로 업데이트되었는지 확인하세요.

PHP 게임 요구사항 구현 가이드 인터넷의 대중화와 발전으로 인해 웹 게임 시장이 점점 더 대중화되고 있습니다. 많은 개발자는 PHP 언어를 사용하여 자신만의 웹 게임을 개발하기를 원하며 게임 요구 사항을 구현하는 것이 핵심 단계입니다. 이 문서에서는 PHP 언어를 사용하여 일반적인 게임 요구 사항을 구현하는 방법을 소개하고 특정 코드 예제를 제공합니다. 1. 게임 캐릭터 만들기 웹게임에서 게임 캐릭터는 매우 중요한 요소입니다. 이름, 레벨, 경험치 등 게임 캐릭터의 속성을 정의하고, 이를 운용할 수 있는 방법을 제공해야 합니다.

오늘날의 소프트웨어 개발 분야에서 효율적이고 간결하며 동시성이 뛰어난 프로그래밍 언어인 Golang(Go 언어)은 점점 더 개발자들의 선호를 받고 있습니다. 풍부한 표준 라이브러리와 효율적인 동시성 기능으로 인해 게임 개발 분야에서 주목받는 선택이 되었습니다. 이 기사에서는 게임 개발에 Golang을 사용하는 방법을 살펴보고 특정 코드 예제를 통해 Golang의 강력한 가능성을 보여줍니다. 1. 게임 개발에서 Golang의 장점 Golang은 정적인 유형의 언어로서 대규모 게임 시스템을 구축하는 데 사용됩니다.

Golang에서 정확한 나눗셈 작업을 구현하는 것은 특히 재무 계산과 관련된 시나리오 또는 고정밀 계산이 필요한 기타 시나리오에서 일반적인 요구 사항입니다. Golang에 내장된 나눗셈 연산자 "/"는 부동 소수점 수에 대해 계산되며 때로는 정밀도가 손실되는 문제가 있습니다. 이 문제를 해결하기 위해 타사 라이브러리나 사용자 정의 기능을 사용하여 정확한 분할 작업을 구현할 수 있습니다. 일반적인 접근 방식은 분수 표현을 제공하고 정확한 나눗셈 연산을 구현하는 데 사용할 수 있는 math/big 패키지의 Rat 유형을 사용하는 것입니다.

Oracle API 통합 전략 분석: 시스템 간의 원활한 통신을 위해서는 특정 코드 예제가 필요합니다. 오늘날 디지털 시대에 내부 기업 시스템은 서로 통신하고 데이터를 공유해야 하며 Oracle API는 원활한 통신을 돕는 중요한 도구 중 하나입니다. 시스템 간 통신. 이 기사에서는 OracleAPI의 기본 개념과 원칙부터 시작하여 API 통합 전략을 살펴보고 마지막으로 독자가 OracleAPI를 더 잘 이해하고 적용할 수 있도록 구체적인 코드 예제를 제공합니다. 1. 기본 오라클 API

실시간 프로그래밍 지침을 제공할 수 없어서 정말 죄송합니다. 하지만 PHP를 사용하여 SaaS를 구현하는 방법을 더 잘 이해할 수 있도록 코드 예제를 제공할 수 있습니다. 다음은 "PHP를 사용하여 SaaS 구현: 종합 분석"이라는 제목의 1,500자 이내의 기사입니다. 오늘날의 정보화 시대에 SaaS(Software as a Service)는 기업과 개인이 소프트웨어에 액세스하는 보다 유연하고 편리한 방법을 제공하는 주류가 되었습니다. SaaS를 사용하면 사용자가 온프레미스에 있을 필요가 없습니다.
