Smarty 3.17+ 搭配 zend framework1.11.11+ 最新配置方案

牢骚两句:马上过年了从事Web PHP方向的开发又一年了 到现在为止也小两年了,基本的也都说的过去但是系统的学习还没有进行过。要想晋级必须功底扎实同时有拿得出手的绝活。忘了从哪里听来的了毕业五年的状况基 本上决定了一个人的职业生涯的情况。所以在断断续续的浮躁,冲动,堕落中我该做点事情了,公司里面有自己的框架所以对zendframework的学习只 是在培训的时候粗略的过了一边。居安思危,一定不能松懈,特别是现在跳槽的情况下zend 还是一个高级的必备的一项技能。所以就重新拾起zendframework。

现在网上的配置都是smarty2+ zend1.0x的 教程都不能用了  所以就自己整理了下一个国外的blog的一个配置 这样翻译过来 方便大家使用   水平有限请多见谅

另源码包已经打包上传:里面包括了lib库 和配置文件   昨天自己玩zend 的时候怎么都无法访问其他的action 后来发现是apache 的 allowOveride none 没有更改 这里小提醒下

zend的环境要求 rewrite 模块 http.conf 中 AllowOverride None 要改成AllowOverride All  php 的pdo_mysql 要开启 至于怎么开启 这个就不在这里说了 谷歌下就可可以找到很多 刚开始我用百度 全部是一篇文章 蛋疼………………….

原文地址:http://gediminasm.org/article/smarty-3-extension-for-zend-framework#action

译文:

Zend 框架延伸 Smarty 3 使用

Smarty 3 和 zend 的扩展很容易整合,并且完全兼容视图和布局模版支持的所有标准功能,如模块和查看 AJAX,JSON,XML。 与现有的smarty 3 的功能没有冲突

 

特点:

标准规则的布局和视图渲染

每个模块的静态模版路径

所有的帮助支持,包括ajax,json xml 上下文

 

第一步:下载相应的库文件 Smarty 3 + zend 1.11.+

初始化zendFramework后的默认目录结构应该是(记住新的zendFramework官方的入口在myapp/public/index.php)

  1. /myapp
  2.     /application
  3.         /configs
  4.             application.ini
  5.         /modules
  6.         Bootstrap.php
  7.     /library
  8.         /Smarty
  9.             /plugins
  10.             /sysplugins
  11.             /debug.tpl
  12.             /Smarty.class.php
  13.     /public

 

配置文件的内容如下

  1. [production]
  2. phpSettings.display_startup_errors = 0
  3. phpSettings.display_errors = 0
  4. bootstrap.path = APPLICATION_PATH “/Bootstrap.php”
  5. bootstrap.class = “Bootstrap”
  6. resources.frontController.moduleDirectory = APPLICATION_PATH “/modules”
  7. resources.frontController.moduleDefault = “default”
  8. resources.layout.layout = “layout”
  9. resources.view[] =
  10. ; — Autoloading Prefixes —
  11. autoloaderNamespaces.extension[] = “Ext_”
  12. ; — Smarty —
  13. smarty.caching = 1
  14. smarty.cache_lifetime = 14400 ; 4 hours
  15. smarty.template_dir = APPLICATION_PATH “/templates/”
  16. smarty.compile_dir = APPLICATION_PATH “/tmp/smarty_compile/”
  17. smarty.config_dir = “”
  18. smarty.cache_dir = APPLICATION_PATH “/tmp/smarty_cache/”
  19. smarty.left_delimiter = “{“
  20. smarty.right_delimiter = “}”
  21. [staging : production]
  22. [testing : production]
  23. phpSettings.display_startup_errors = 1
  24. phpSettings.display_errors = 1
  25. [development : production]
  26. phpSettings.display_startup_errors = 1
  27. phpSettings.display_errors = 1
  28. resources.frontController.params.displayExceptions = 1
  29. smarty.caching = 0

 

这时候的目录结构应该是这个样子

  1. /myapp
  2.     /application
  3.         /configs
  4.             application.ini
  5.         /modules
  6.             /default
  7.                 /controllers
  8.                     …
  9.                 /views
  10.                     …
  11.         /tmp
  12.         Bootstrap.php
  13.     /library
  14.         /Smarty
  15.             /plugins
  16.             /sysplugins
  17.             /debug.tpl
  18.             /Smarty.class.php
  19.         /Ext
  20.     /public

 

最重要的一步 创建smarty.php 载入文件

目录地址myapp/library/Ext/View/Smarty.php

内容如下

  1. /**
  2.  * Smarty template engine integration into Zend Framework
  3.  * Some ideas borrowed from http://devzone.zend.com/article/120
  4.  */
  5. class Ext_View_Smarty extends Zend_View_Abstract
  6. {
  7.     /**
  8.      * Instance of Smarty
  9.      * @var Smarty
  10.      */
  11.     protected $_smarty = null;
  12.     /**
  13.      * Template explicitly set to render in this view
  14.      * @var string
  15.      */
  16.     protected $_customTemplate = ”;
  17.     /**
  18.      * Smarty config
  19.      * @var array
  20.      */
  21.     private $_config = null;
  22.     /**
  23.      * Class definition and constructor
  24.      *
  25.      * Let’s start with the class definition and the constructor part. My class Travello_View_Smarty is extending the Zend_View_Abstract class. In the constructor the parent constructor from Zend_View_Abstract is called first. After that a Smarty object is instantiated, configured and stored in a private attribute.
  26.      * Please note that I use a configuration object from the object store to get the configuration data for Smarty.
  27.      *
  28.      * @param array $smartyConfig
  29.      * @param array $config
  30.      */
  31.     public function __construct($smartyConfig, $config = array())
  32.     {
  33.         $this->_config = $smartyConfig;
  34.         parent::__construct($config);
  35.         $this->_loadSmarty();
  36.     }
  37.     /**
  38.      * Return the template engine object
  39.      *
  40.      * @return Smarty
  41.      */
  42.     public function getEngine()
  43.     {
  44.         return $this->_smarty;
  45.     }
  46.     /**
  47.      * Implement _run() method
  48.      *
  49.      * The method _run() is the only method that needs to be implemented in any subclass of Zend_View_Abstract. It is called automatically within the render() method. My implementation just uses the display() method from Smarty to generate and output the template.
  50.      *
  51.      * @param string $template
  52.      */
  53.     protected function _run()
  54.     {
  55.         $file = func_num_args() > 0 && file_exists(func_get_arg(0)) ? func_get_arg(0) : ”;
  56.         if ($this->_customTemplate || $file) {
  57.             $template = $this->_customTemplate;
  58.             if (!$template) {
  59.                 $template = $file;
  60.             }
  61.             $this->_smarty->display($template);
  62.         } else {
  63.             throw new Zend_View_Exception(‘Cannot render view without any template being assigned or file does not exist’);
  64.         }
  65.     }
  66.     /**
  67.      * Overwrite assign() method
  68.      *
  69.      * The next part is an overwrite of the assign() method from Zend_View_Abstract, which works in a similar way. The big difference is that the values are assigned to the Smarty object and not to the $this->_vars variables array of Zend_View_Abstract.
  70.      *
  71.      * @param string|array $var
  72.      * @return Ext_View_Smarty
  73.      */
  74.     public function assign($var, $value = null)
  75.     {
  76.         if (is_string($var)) {
  77.             $this->_smarty->assign($var, $value);
  78.         } elseif (is_array($var)) {
  79.             foreach ($var as $key => $value) {
  80.                 $this->assign($key, $value);
  81.             }
  82.         } else {
  83.             throw new Zend_View_Exception(‘assign() expects a string or array, got ‘.gettype($var));
  84.         }
  85.         return $this;
  86.     }
  87.     /**
  88.      * Overwrite escape() method
  89.      *
  90.      * The next part is an overwrite of the escape() method from Zend_View_Abstract. It works both for string and array values and also uses the escape() method from the Zend_View_Abstract. The advantage of this is that I don’t have to care about each value of an array to get properly escaped.
  91.      *
  92.      * @param mixed $var
  93.      * @return mixed
  94.      */
  95.     public function escape($var)
  96.     {
  97.         if (is_string($var)) {
  98.             return parent::escape($var);
  99.         } elseif (is_array($var)) {
  100.             foreach ($var as $key => $val) {
  101.                 $var[$key] = $this->escape($val);
  102.             }
  103.         }
  104.         return $var;
  105.     }
  106.     /**
  107.      * Print the output
  108.      *
  109.      * The next method output() is a wrapper on the render() method from Zend_View_Abstract. It just sets some headers before printing the output.
  110.      *
  111.      * @param <type> $name
  112.      */
  113.     public function output($name)
  114.     {
  115.         header(“Expires: Mon, 26 Jul 1997 05:00:00 GMT”);
  116.         header(“Cache-Control: no-cache”);
  117.         header(“Pragma: no-cache”);
  118.         header(“Cache-Control: post-check=0, pre-check=0”, false);
  119.         print parent::render($name);
  120.     }
  121.     /**
  122.      * Use Smarty caching
  123.      *
  124.      * The last two methods were created to simply integrate the Smarty caching mechanism in the View class. With the first one you can check for cached template and with the second one you can set the caching on or of.
  125.      *
  126.      * @param string $template
  127.      * @return bool
  128.      */
  129.     public function isCached($template)
  130.     {
  131.         return $this->_smarty->is_cached($template);
  132.     }
  133.     /**
  134.      * Enable/disable caching
  135.      *
  136.      * @param bool $caching
  137.      * @return Ext_View_Smarty
  138.      */
  139.     public function setCaching($caching)
  140.     {
  141.         $this->_smarty->caching = $caching;
  142.         return $this;
  143.     }
  144.     /**
  145.      * Template getter (return file path)
  146.      * @return string
  147.      */
  148.     public function getTemplate()
  149.     {
  150.         return $this->_customTemplate;
  151.     }
  152.     /**
  153.      * Template filename setter
  154.      * @param string
  155.      * @return Ext_View_Smarty
  156.      */
  157.     public function setTemplate($tpl)
  158.     {
  159.         $this->_customTemplate = $tpl;
  160.         return $this;
  161.     }
  162.     /**
  163.      * Magic setter for Zend_View compatibility. Performs assign()
  164.      *
  165.      * @param string $key
  166.      * @param mixed $val
  167.      */
  168.     public function __set($key, $val)
  169.     {
  170.         $this->assign($key, $val);
  171.     }
  172.     /**
  173.      * Magic getter for Zend_View compatibility. Retrieves template var
  174.      *
  175.      * @param string $key
  176.      * @return mixed
  177.      */
  178.     public function __get($key)
  179.     {
  180.         return $this->_smarty->getTemplateVars($key);
  181.     }
  182.     /**
  183.      * Magic getter for Zend_View compatibility. Removes template var
  184.      *
  185.      * @see View/Zend_View_Abstract::__unset()
  186.      * @param string $key
  187.      */
  188.     public function __unset($key)
  189.     {
  190.         $this->_smarty->clearAssign($key);
  191.     }
  192.     /**
  193.      * Allows testing with empty() and isset() to work
  194.      * Zend_View compatibility. Checks template var for existance
  195.      *
  196.      * @param string $key
  197.      * @return boolean
  198.      */
  199.     public function __isset($key)
  200.     {
  201.         return (null !== $this->_smarty->getTemplateVars($key));
  202.     }
  203.     /**
  204.      * Zend_View compatibility. Retrieves all template vars
  205.      *
  206.      * @see Zend_View_Abstract::getVars()
  207.      * @return array
  208.      */
  209.     public function getVars()
  210.     {
  211.         return $this->_smarty->getTemplateVars();
  212.     }
  213.     /**
  214.      * Updates Smarty’s template_dir field with new value
  215.      *
  216.      * @param string $dir
  217.      * @return Ext_View_Smarty
  218.      */
  219.     public function setTemplateDir($dir)
  220.     {
  221.         $this->_smarty->setTemplateDir($dir);
  222.         return $this;
  223.     }
  224.     /**
  225.      * Adds another Smarty template_dir to scan for templates
  226.      *
  227.      * @param string $dir
  228.      * @return Ext_View_Smarty
  229.      */
  230.     public function addTemplateDir($dir)
  231.     {
  232.         $this->_smarty->addTemplateDir($dir);
  233.         return $this;
  234.     }
  235.     /**
  236.      * Adds another Smarty plugin directory to scan for plugins
  237.      *
  238.      * @param string $dir
  239.      * @return Ext_View_Smarty
  240.      */
  241.     public function addPluginDir($dir)
  242.     {
  243.         $this->_smarty->addPluginsDir($dir);
  244.         return $this;
  245.     }
  246.     /**
  247.      * Zend_View compatibility. Removes all template vars
  248.      *
  249.      * @see View/Zend_View_Abstract::clearVars()
  250.      * @return Ext_View_Smarty
  251.      */
  252.     public function clearVars()
  253.     {
  254.         $this->_smarty->clearAllAssign();
  255.         $this->assign(‘this’, $this);
  256.         return $this;
  257.     }
  258.     /**
  259.      * Zend_View compatibility. Add the templates dir
  260.      *
  261.      * @see View/Zend_View_Abstract::addBasePath()
  262.      * @return Ext_View_Smarty
  263.      */
  264.     public function addBasePath($path, $classPrefix = ‘Zend_View’)
  265.     {
  266.         parent::addBasePath($path, $classPrefix);
  267.         $this->addScriptPath($path . ‘/templates’);
  268.         $this->addTemplateDir($path . ‘/templates/static’);
  269.         return $this;
  270.     }
  271.     /**
  272.      * Zend_View compatibility. Set the templates dir instead of scripts
  273.      *
  274.      * @see View/Zend_View_Abstract::setBasePath()
  275.      * @return Ext_View_Smarty
  276.      */
  277.     public function setBasePath($path, $classPrefix = ‘Zend_View’)
  278.     {
  279.         parent::setBasePath($path, $classPrefix);
  280.         $this->setScriptPath($path . ‘/templates’);
  281.         $this->addTemplateDir($path . ‘/templates/static’);
  282.         return $this;
  283.     }
  284.     /**
  285.      * Magic clone method, on clone create diferent smarty object
  286.      */
  287.     public function __clone() {
  288.         $this->_loadSmarty();
  289.     }
  290.     /**
  291.      * Initializes the smarty and populates config params
  292.      *
  293.      * @throws Zend_View_Exception
  294.      * @return void
  295.      */
  296.     private function _loadSmarty()
  297.     {
  298.         if (!class_exists(‘Smarty’, true)) {
  299.             require_once ‘Smarty/Smarty.class.php’;
  300.         }
  301.         $this->_smarty = new Smarty();
  302.         if ($this->_config === null) {
  303.             throw new Zend_View_Exception(“Could not locate Smarty config – node ‘smarty’ not found”);
  304.         }
  305.         $this->_smarty->caching = $this->_config[‘caching’];
  306.         $this->_smarty->cache_lifetime = $this->_config[‘cache_lifetime’];
  307.         $this->_smarty->template_dir = $this->_config[‘template_dir’];
  308.         $this->_smarty->compile_dir = $this->_config[‘compile_dir’];
  309.         $this->_smarty->config_dir = $this->_config[‘config_dir’];
  310.         $this->_smarty->cache_dir = $this->_config[‘cache_dir’];
  311.         $this->_smarty->left_delimiter = $this->_config[‘left_delimiter’];
  312.         $this->_smarty->right_delimiter = $this->_config[‘right_delimiter’];
  313.         $this->assign(‘this’, $this);
  314.     }
  315. }

 

现在目录结构是这个样子

  1. /myapp
  2.     …
  3.     /library
  4.         /Smarty
  5.             /plugins
  6.             /sysplugins
  7.             /debug.tpl
  8.             /Smarty.class.php
  9.         /Ext
  10.             /View
  11.                 Smarty.php
  12.     /public

 

BootStrap文件的内容如下

myapp/application/Bootstrap.php

  1. class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
  2. {
  3.     /**
  4.      * Bootstrap Smarty view
  5.      */
  6.     protected function _initView()
  7.     {
  8.         // initialize smarty view
  9.         $view = new Ext_View_Smarty($this->getOption(‘smarty’));
  10.         // setup viewRenderer with suffix and view
  11.         $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(‘ViewRenderer’);
  12.         $viewRenderer->setViewSuffix(‘tpl’);
  13.         $viewRenderer->setView($view);
  14.         // ensure we have layout bootstraped
  15.         $this->bootstrap(‘layout’);
  16.         // set the tpl suffix to layout also
  17.         $layout = Zend_Layout::getMvcInstance();
  18.         $layout->setViewSuffix(‘tpl’);
  19.         return $view;
  20.     }
  21. }

现在目录结构

  1. /myapp
  2.     /application
  3.         /configs
  4.             application.ini
  5.         /modules
  6.             /default
  7.                 /controllers
  8.                     IndexController.php
  9.                     ErrorController.php
  10.                 /views
  11.                     /templates
  12.                         /error
  13.                             error.tpl
  14.                         /index
  15.                             index.tpl
  16.                         /static
  17.                             header.tpl
  18.                         layout.tpl
  19.         Bootstrap.php

 

indexController的内容

myapp/application/controllers/IndexController.php

  1. <?php
  2. class IndexController extends Zend_Controller_Action
  3. {
  4.     public function indexAction()
  5.     {
  6.         $this->view->hello = ‘Hello Smarty 3’;
  7.     }
  8. }

 

创建index/index.tpl

myapp/application/view/templates/index/index.tpl

  1. <!DOCTYPE p PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
  2. <html>
  3. <head>
  4. <meta http-equiv=”Content-Type” content=”text/html;charset=utf-8;”>
  5. </head>
  6. <body>
  7. <p>{$hello}</p>
  8. <p>dont forget to visit <a target=”_blank” href=”http://blog.csdn.net/JustBeBetter”>代码顽主BLOG</a>
  9. </p><p><a href=”{$this->url([‘controller’ => ‘index’, ‘action’ => ‘index’])}”>home</a></p>
  10. </body>
  11. </html>

 

 

创建error/error.tpl

myapp/application/view/templates/error/error.tpl

  1. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
  2. <title>Zend Framework Default Application</title>
  3. <h1>An error occurred</h1>
  4. <h2>{$this->message}</h2>
  5. {if $this->exception}
  6. <h3>Exception information:</h3>
  7. <p>
  8.     <b>Message:</b> {$this->exception->getMessage()}
  9. </p>
  10. <h3>Stack trace:</h3>
  11. <pre>{$this->exception->getTraceAsString()}
  12. </pre>
  13. <h3>Request Parameters:</h3>
  14. <pre>{var_export($this->request->getParams(), true)}
  15. </pre>
  16. {/if}

 

创建 头部文件

myapp/application/view/templates/static/header.tpl

  1. <div id=”header”>
  2.     {include file=”header.tpl”}
  3. </div>
  4. {$this->layout()->content}

创建头文件

  1. header

现在你可以访问你的网站了 对了 入口在publi目录下哦

在上班所以有些粗糙:如果有看不懂的请参考原文

下面是我试验过的例子的源代码 下载后直接使用就可以

源码地址:http://download.csdn.net/detail/justbebetter/4001055

11 thoughts on “Smarty 3.17+ 搭配 zend framework1.11.11+ 最新配置方案

  1. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is needed to get set up? I’m assuming having
    a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100% certain.
    Any recommendations or advice would be greatly
    appreciated. Thank you

  2. Nice post. I was checking continuously this blog and
    I’m inspired! Very helpful info particularly the last section :) I care for such info a lot. I was looking for this particular information for a long time. Thanks and best of luck.

  3. Wow, wonderful weblog format! How lengthy have you been
    blogging for? you make blogging glance easy.

    The full glance of your web site is fantastic, let alone the content!

  4. Heya I’m for the first time here. I came across this board and I find It really useful & it helped me out much. I hope to give something back and help others like you aided me.

  5. The article provides established useful to us. It’s quite
    informative and you are naturally very knowledgeable in this region.
    You possess popped our eyes in order to varying thoughts about this topic with interesting and solid articles.

  6. Very nice post. I just stumbled upon your blog and wished to say that I’ve really enjoyed surfing around your blog posts. After all I’ll be subscribing to your
    rss feed and I hope you write again very soon!

  7. Tremendous things here. I am very satisfied to look your article.
    Thank you a lot and I am looking ahead to contact you. Will
    you kindly drop me a mail?

  8. It’s truly very difficult in this full of activity life to listen news on Television, so I only use the web for that purpose, and take the latest news.

  9. 感谢博主的分享,清闲的时候看看还是不错的,希望多多更新。

Comments are closed.