Table des matières
Zend Framework实现Zend_View集成Smarty模板系统的方法,zend_viewsmarty
您可能感兴趣的文章:
Maison développement back-end tutoriel 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);
}

Copier après la connexion

集成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);
  }
}

Copier après la connexion

/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

Copier après la connexion

/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;
  }
}

Copier après la connexion

/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');
  }
}

Copier après la connexion

/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>

Copier après la connexion

如果需要配置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']);
    }
}

Copier après la connexion

更多关于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模板系统的方法。分享给大家...
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Problèmes d'installation de Microsoft NET Framework, code d'erreur 0x800c0006, correctif Problèmes d'installation de Microsoft NET Framework, code d'erreur 0x800c0006, correctif May 05, 2023 pm 04:01 PM

.NET Framework 4 est requis par les développeurs et les utilisateurs finaux pour exécuter les dernières versions des applications sous Windows. Cependant, lors du téléchargement et de l'installation de .NET Framework 4, de nombreux utilisateurs se sont plaints de l'arrêt du programme d'installation à mi-chemin, affichant le message d'erreur suivant : « .NET Framework 4 n'a pas été installé car le téléchargement a échoué avec le code d'erreur 0x800c0006 ». Si vous le rencontrez également lors de l'installation de .NETFramework4 sur votre appareil, vous êtes au bon endroit

Comment identifier les problèmes de mise à niveau de Windows à l'aide de SetupDiag sous Windows 11/10 Comment identifier les problèmes de mise à niveau de Windows à l'aide de SetupDiag sous Windows 11/10 Apr 17, 2023 am 10:07 AM

Chaque fois que votre PC Windows 11 ou Windows 10 rencontre un problème de mise à niveau ou de mise à jour, vous verrez généralement un code d'erreur indiquant la raison réelle de l'échec. Cependant, une confusion peut parfois survenir lorsqu'une mise à niveau ou une mise à jour échoue sans qu'un code d'erreur ne s'affiche. Grâce à des codes d'erreur pratiques, vous savez exactement où se situe le problème afin que vous puissiez essayer de le résoudre. Mais comme aucun code d’erreur n’apparaît, il devient difficile d’identifier le problème et de le résoudre. Cela prendra beaucoup de temps pour simplement découvrir la raison de l'erreur. Dans ce cas, vous pouvez essayer d'utiliser un outil dédié appelé SetupDiag fourni par Microsoft qui vous aide à identifier facilement la véritable raison de l'erreur.

SCNotification a cessé de fonctionner [5 étapes pour y remédier] SCNotification a cessé de fonctionner [5 étapes pour y remédier] May 17, 2023 pm 09:35 PM

En tant qu'utilisateur Windows, vous rencontrerez probablement une erreur SCNotification a cessé de fonctionner à chaque démarrage de votre ordinateur. SCNotification.exe est un fichier de notification système Microsoft qui plante à chaque démarrage de votre PC en raison d'erreurs d'autorisation et de pannes de réseau. Cette erreur est également connue sous son nom d’événement problématique. Vous ne verrez donc peut-être pas cela comme un arrêt de SCNotification, mais comme un bug clr20r3. Dans cet article, nous explorerons toutes les étapes à suivre pour réparer SCNotification a cessé de fonctionner afin qu'il ne vous dérange plus. Qu'est-ce que SCNotification.e

Développement Laravel : Comment générer des vues avec Laravel View ? Développement Laravel : Comment générer des vues avec Laravel View ? Jun 14, 2023 pm 03:28 PM

Laravel est actuellement l'un des frameworks PHP les plus populaires et ses puissantes capacités de génération de vues sont impressionnantes. Une vue est une page ou un élément visuel affiché à l'utilisateur dans une application Web, qui contient du code tel que HTML, CSS et JavaScript. LaravelView permet aux développeurs d'utiliser un langage de modèle structuré pour créer des pages Web et générer les vues correspondantes via les contrôleurs et le routage. Dans cet article, nous explorerons comment générer des vues à l'aide de LaravelView. 1. Quoi

Microsoft .NET Framework 4.5.2, 4.6 et 4.6.1 cessera de prendre en charge en avril 2022 Microsoft .NET Framework 4.5.2, 4.6 et 4.6.1 cessera de prendre en charge en avril 2022 Apr 17, 2023 pm 02:25 PM

Les utilisateurs de Microsoft Windows qui ont installé Microsoft.NET version 4.5.2, 4.6 ou 4.6.1 doivent installer une version plus récente de Microsoft Framework s'ils souhaitent que Microsoft prenne en charge le framework via de futures mises à jour de produit. Selon Microsoft, les trois frameworks cesseront de prendre en charge le 26 avril 2022. Une fois la date de support terminée, le produit ne recevra plus de « correctifs de sécurité ni de support technique ». La plupart des appareils domestiques sont tenus à jour grâce aux mises à jour Windows. Ces appareils disposent déjà de versions plus récentes de frameworks, telles que .NET Framework 4.8. Les appareils qui ne se mettent pas à jour automatiquement peuvent

KB5012643 pour Windows 11 interrompt les applications .NET Framework 3.5 KB5012643 pour Windows 11 interrompt les applications .NET Framework 3.5 May 09, 2023 pm 01:07 PM

Cela fait une semaine que nous parlions du nouveau bug du mode sans échec affectant les utilisateurs ayant installé KB5012643 pour Windows 11. Ce problème embêtant n'apparaissait pas sur la liste des problèmes connus publiée par Microsoft le jour du lancement, prenant ainsi tout le monde par surprise. Eh bien, juste au moment où vous pensiez que les choses ne pourraient pas empirer, Microsoft lâche une autre bombe pour les utilisateurs qui ont installé cette mise à jour cumulative. Windows 11 Build 22000.652 pose davantage de problèmes. La société de technologie avertit donc les utilisateurs de Windows 11 qu'ils pourraient rencontrer des problèmes lors du lancement et de l'utilisation de certaines applications .NET Framework 3.5. Cela vous semble familier ? Mais s'il te plaît, ne sois pas surpris

Comment utiliser l'ACL (Access Control List) pour le contrôle des autorisations dans Zend Framework Comment utiliser l'ACL (Access Control List) pour le contrôle des autorisations dans Zend Framework Jul 29, 2023 am 09:24 AM

Comment utiliser l'ACL (AccessControlList) pour le contrôle des autorisations dans Zend Framework Introduction : Dans une application Web, le contrôle des autorisations est une fonction cruciale. Il garantit que les utilisateurs ne peuvent accéder qu'aux pages et fonctionnalités auxquelles ils sont autorisés à accéder et empêche tout accès non autorisé. Le framework Zend fournit un moyen pratique d'implémenter le contrôle des autorisations, en utilisant le composant ACL (AccessControlList). Cet article explique comment utiliser l'ACL dans Zend Framework.

Framework d'implémentation PHP : Tutoriel de mise en route de Zend Framework Framework d'implémentation PHP : Tutoriel de mise en route de Zend Framework Jun 19, 2023 am 08:09 AM

Framework d'implémentation PHP : tutoriel d'introduction à ZendFramework ZendFramework est un framework de site Web open source développé par PHP et actuellement maintenu par ZendTechnologies. ZendFramework adopte le modèle de conception MVC et fournit une série de bibliothèques de code réutilisables pour servir l'implémentation d'applications Web2.0 et Web Serve. ZendFramework est très populaire et respecté par les développeurs PHP et propose une large gamme de

See all articles