热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ZendFramework实现Zend_View集成Smarty模板系统的方法

这篇文章主要介绍了ZendFramework实现Zend_View集成Smarty模板系统的方法,详细分析了视图组件Zend_View使用接口Zend_View_Interface继承Smarty的原理与实现技巧,需要的朋友可以参考下

本文实例讲述了Zend Framework实现Zend_View集成Smarty模板系统的方法。分享给大家供大家参考,具体如下:

Zend_View抽象出了Zend_View_Interface,可以让我们集成不同的视图解决方案,例如可以集成smarty。要在zend中使用其他视图系统作为视图,只要实现Zend_View_Interface接口即可。

Zend_View_Interface的接口定义:

<&#63;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

<&#63;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

<&#63;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

<&#63;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








{$book}
{$author}



如果需要配置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程序设计有所帮助。


推荐阅读
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文介绍了使用cacti监控mssql 2005运行资源情况的操作步骤,包括安装必要的工具和驱动,测试mssql的连接,配置监控脚本等。通过php连接mssql来获取SQL 2005性能计算器的值,实现对mssql的监控。详细的操作步骤和代码请参考附件。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 解决VS写C#项目导入MySQL数据源报错“You have a usable connection already”问题的正确方法
    本文介绍了在VS写C#项目导入MySQL数据源时出现报错“You have a usable connection already”的问题,并给出了正确的解决方法。详细描述了问题的出现情况和报错信息,并提供了解决该问题的步骤和注意事项。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • 2018年人工智能大数据的爆发,学Java还是Python?
    本文介绍了2018年人工智能大数据的爆发以及学习Java和Python的相关知识。在人工智能和大数据时代,Java和Python这两门编程语言都很优秀且火爆。选择学习哪门语言要根据个人兴趣爱好来决定。Python是一门拥有简洁语法的高级编程语言,容易上手。其特色之一是强制使用空白符作为语句缩进,使得新手可以快速上手。目前,Python在人工智能领域有着广泛的应用。如果对Java、Python或大数据感兴趣,欢迎加入qq群458345782。 ... [详细]
  • 初识java关于JDK、JRE、JVM 了解一下 ... [详细]
  • PRML读书会第十四章 Combining Models(committees,Boosting,AdaBoost,决策树,条件混合模型)...
    主讲人网神(新浪微博:豆角茄子麻酱凉面)网神(66707180)18:57:18大家好,今天我们讲一下第14章combiningmodel ... [详细]
  • ElasticSearch成功安装完毕。 测试数据添加出现{  error:{    root_cause ... [详细]
  • 基于SpringBoot打造在线教育系统(6)– 二级分类模块UI篇
    这一节来做二级分类,为了快速开发,一级分类只做新增,暂时不考虑修改和删除,如果一定要删,就去数据库删吧。我们接下来,需要通过一级分类,获取所有的二级分类。开始 ... [详细]
  • 1、DashAPI文档Dash是一个API文档浏览器,使用户可以使用离线功能即时搜索无数API。程序员使用Dash可访问iOS,MacOS, ... [详细]
author-avatar
白小貓貓兒是青咔咔-
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有