목차
Zend Framework实现Zend_View集成Smarty模板系统的方法,zend_viewsmarty
您可能感兴趣的文章:
백엔드 개발 PHP 튜토리얼 Zend Framework实现Zend_View集成Smarty模板系统的方法,zend_viewsmarty_PHP教程

Zend Framework实现Zend_View集成Smarty模板系统的方法,zend_viewsmarty_PHP教程

Jul 12, 2016 am 08:57 AM
framework smarty view zend

Zend Framework实现Zend_View集成Smarty模板系统的方法,zend_viewsmarty

本文实例讲述了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

<!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程序设计有所帮助。

您可能感兴趣的文章:

  • Zend Framework教程之Zend_Controller_Plugin插件用法详解
  • Zend Framework教程之响应对象的封装Zend_Controller_Response实例详解
  • Zend Framework教程之请求对象的封装Zend_Controller_Request实例详解
  • Zend Framework教程之动作的基类Zend_Controller_Action详解
  • Zend Framework教程之分发器Zend_Controller_Dispatcher用法详解
  • Zend Framework教程之前端控制器Zend_Controller_Front用法详解
  • Zend Framework动作助手Redirector用法实例详解
  • Zend Framework动作助手Url用法详解
  • Zend Framework动作助手Json用法实例分析
  • Zend Framework动作助手FlashMessenger用法详解
  • Zend Framework创建自己的动作助手详解
  • Zend Framework动作助手(Zend_Controller_Action_Helper)用法详解
  • Zend Framework教程之路由功能Zend_Controller_Router详解

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1106903.htmlTechArticleZend Framework实现Zend_View集成Smarty模板系统的方法,zend_viewsmarty 本文实例讲述了Zend Framework实现Zend_View集成Smarty模板系统的方法。分享给大家...
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

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

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

Microsoft NET Framework 설치 문제 오류 코드 0x800c0006 수정 Microsoft NET Framework 설치 문제 오류 코드 0x800c0006 수정 May 05, 2023 pm 04:01 PM

.NET Framework 4는 개발자와 최종 사용자가 Windows에서 최신 버전의 애플리케이션을 실행하는 데 필요합니다. 그러나 .NET Framework 4를 다운로드하고 설치하는 동안 많은 사용자가 설치 프로그램이 중간에 중지되고 "오류 코드 0x800c0006으로 인해 다운로드에 실패했기 때문에 .NET Framework 4가 설치되지 않았습니다"라는 오류 메시지가 표시된다고 불평했습니다. 장치에 .NETFramework4를 설치하는 동안에도 이 문제가 발생한다면 올바른 위치에 있는 것입니다.

Windows 11/10에서 SetupDiag를 사용하여 Windows 업그레이드 문제를 식별하는 방법 Windows 11/10에서 SetupDiag를 사용하여 Windows 업그레이드 문제를 식별하는 방법 Apr 17, 2023 am 10:07 AM

Windows 11 또는 Windows 10 PC에 업그레이드 또는 업데이트 문제가 있을 때마다 일반적으로 실패의 실제 원인을 나타내는 오류 코드가 표시됩니다. 그러나 오류 코드가 표시되지 않고 업그레이드나 업데이트가 실패하면 혼란이 발생할 수 있습니다. 편리한 오류 코드를 사용하면 문제가 어디에 있는지 정확히 알 수 있으므로 문제를 해결할 수 있습니다. 하지만 오류 코드가 나타나지 않기 때문에 문제를 식별하고 해결하기가 어렵습니다. 단순히 오류의 원인을 찾는 데 많은 시간이 걸립니다. 이 경우 오류의 실제 원인을 쉽게 식별하는 데 도움이 되는 Microsoft에서 제공하는 SetupDiag라는 전용 도구를 사용해 볼 수 있습니다.

SCNotification이 작동을 멈췄습니다. [수정을 위한 5단계] SCNotification이 작동을 멈췄습니다. [수정을 위한 5단계] May 17, 2023 pm 09:35 PM

Windows 사용자는 컴퓨터를 시작할 때마다 SCNotification이 작동을 중지했습니다. 오류가 발생할 수 있습니다. SCNotification.exe는 권한 오류 및 네트워크 오류로 인해 PC를 시작할 때마다 충돌이 발생하는 Microsoft 시스템 알림 파일입니다. 이 오류는 문제가 있는 이벤트 이름으로도 알려져 있습니다. 따라서 이를 SCNotification의 작동이 중지된 것으로 표시되지 않고 버그 clr20r3으로 표시될 수 있습니다. 이 기사에서는 SCNotification이 작동을 중지하여 다시 귀찮게 하지 않도록 수정하기 위해 취해야 할 모든 단계를 살펴보겠습니다. SCNotification.e는 무엇입니까

Laravel 개발: Laravel View를 사용하여 뷰를 생성하는 방법은 무엇입니까? Laravel 개발: Laravel View를 사용하여 뷰를 생성하는 방법은 무엇입니까? Jun 14, 2023 pm 03:28 PM

Laravel은 현재 가장 인기 있는 PHP 프레임워크 중 하나이며 강력한 뷰 생성 기능이 인상적입니다. 보기는 웹 애플리케이션에서 사용자에게 표시되는 페이지 또는 시각적 요소로, HTML, CSS, JavaScript와 같은 코드가 포함되어 있습니다. LaravelView를 사용하면 개발자는 구조화된 템플릿 언어를 사용하여 웹 페이지를 구축하고 컨트롤러 및 라우팅을 통해 해당 뷰를 생성할 수 있습니다. 이번 글에서는 LaravelView를 사용하여 뷰를 생성하는 방법을 살펴보겠습니다. 1. 무엇

Microsoft .NET Framework 4.5.2, 4.6 및 4.6.1은 2022년 4월에 지원이 종료됩니다. Microsoft .NET Framework 4.5.2, 4.6 및 4.6.1은 2022년 4월에 지원이 종료됩니다. Apr 17, 2023 pm 02:25 PM

Microsoft.NET 버전 4.5.2, 4.6 또는 4.6.1을 설치한 Microsoft Windows 사용자가 Microsoft에서 향후 제품 업데이트를 통해 프레임워크를 지원하도록 하려면 최신 버전의 Microsoft Framework를 설치해야 합니다. Microsoft에 따르면 세 가지 프레임워크 모두 2022년 4월 26일에 지원이 중단됩니다. 지원 날짜가 종료되면 해당 제품은 "보안 수정 또는 기술 지원"을 받을 수 없습니다. 대부분의 가정용 장치는 Windows 업데이트를 통해 최신 상태로 유지됩니다. 이러한 장치에는 .NET Framework 4.8과 같은 최신 버전의 프레임워크가 이미 설치되어 있습니다. 자동으로 업데이트되지 않는 장치는

Windows 11용 KB5012643으로 인해 .NET Framework 3.5 앱이 중단됨 Windows 11용 KB5012643으로 인해 .NET Framework 3.5 앱이 중단됨 May 09, 2023 pm 01:07 PM

Windows 11용 KB5012643을 설치한 사용자에게 영향을 미치는 새로운 안전 모드 버그에 대해 이야기한 지 일주일이 지났습니다. 이 성가신 문제는 Microsoft가 출시일에 게시한 알려진 문제 목록에 나타나지 않아 모두를 놀라게 했습니다. 글쎄, 상황이 더 이상 악화될 수 없다고 생각했을 때 Microsoft는 이 누적 업데이트를 설치한 사용자에게 또 다른 폭탄을 떨어뜨렸습니다. Windows 11 빌드 22000.652로 인해 더 많은 문제 발생 따라서 기술 회사는 Windows 11 사용자에게 일부 .NET Framework 3.5 응용 프로그램을 시작하고 사용하는 데 문제가 발생할 수 있다고 경고합니다. 익숙한 것 같나요? 하지만 놀라지 마세요.

Zend Framework에서 권한 제어를 위해 ACL(Access Control List)을 사용하는 방법 Zend Framework에서 권한 제어를 위해 ACL(Access Control List)을 사용하는 방법 Jul 29, 2023 am 09:24 AM

Zend Framework에서 권한 제어를 위해 ACL(AccessControlList)을 사용하는 방법 소개: 웹 애플리케이션에서 권한 제어는 중요한 기능입니다. 이는 사용자가 액세스 권한이 있는 페이지와 기능에만 액세스할 수 있도록 하고 무단 액세스를 방지합니다. Zend 프레임워크는 ACL(AccessControlList) 구성 요소를 사용하여 권한 제어를 구현하는 편리한 방법을 제공합니다. 이 기사에서는 Zend Framework에서 ACL을 사용하는 방법을 소개합니다.

PHP 구현 프레임워크: Zend 프레임워크 시작 튜토리얼 PHP 구현 프레임워크: Zend 프레임워크 시작 튜토리얼 Jun 19, 2023 am 08:09 AM

PHP 구현 프레임워크: ZendFramework 입문 튜토리얼 ZendFramework는 PHP에서 개발하고 현재 ZendTechnologies에서 유지 관리하는 오픈 소스 웹 사이트 프레임워크입니다. ZendFramework는 MVC 디자인 패턴을 채택하고 Web2.0 애플리케이션 및 Web Serve 구현을 지원하기 위한 재사용 가능한 코드 라이브러리 시리즈를 제공합니다. ZendFramework는 PHP 개발자들에게 매우 인기 있고 존경받고 있으며 다양한 기능을 갖추고 있습니다.

See all articles