现在的位置: 首页 > 综合 > 正文

走进Zend Framework框架编程(六):视图(2)

2013年08月03日 ⁄ 综合 ⁄ 共 7477字 ⁄ 字号 评论关闭

6.6视图脚本的变量转义输出(escaping output)
视图脚本得到变量以后,需要通过转义进行输出,变成页面可以显示的Html代码。
输出语句的格式:
echo $this->escape($this->variable);
$variable变量是在视图脚本里用render方法传递过来的。
一般情况下,传递的变量是通过PHP的 htmlspecialchars()函数转义的。而我们也可以实现我们自己的转义函数。请参考以上“使用回调函数”示例。

6.7视图脚本的模板系统—操作PHPLib类型的模板
模板系统进一步完美的实现了视图与程序逻辑的分离。视图脚本可以完美的操作PHPLib等类型的模板。
6.7.1PHPlib的安装和调用
为了测试下面的示例,我们必须安装PHPLib模板系统到我们的环境中。从网上下载到phplib-7.4.ZIP安装压缩包,解压到安装ZEND的library文件夹下,就完成了安装。
为了在ZF的视图脚本里调用得到模板类文件,必须在引导文件Index.php的set_include_path部分添加PHPLib模板类库文件夹phplib-7.4/php到搜索路径中。以下示例同时包含了Smarty模板引擎的类库文件的搜索路径:
set_include_path('.' .
  PATH_SEPARATOR . '../library/'.
  PATH_SEPARATOR . '../library/phplib-7.4/php/'.
  PATH_SEPARATOR . '../library/Smarty-2.6.19/libs/'.
  PATH_SEPARATOR . 'models/'.
  PATH_SEPARATOR . get_include_path()
);
注意,所有路径都是以引导文件所在文件夹作为参照的。尽管视图文件里所在文件夹不是引导文件所在根目录,但在视图文件里包含PHPLib类库文件的语句include_once 'template.inc';仍然是以引导文件所在目录作为参照的。

6.7.2在视图文件里调用PHPLib模板
首先包含PHPLib类库文件,然后声明模板类的一个实例。使用模板类,首先需要指定一些属性,比如指定模板所在路径,指定模板文件等,然后用set_var传递模板变量,最后用parse方法调用模板文件。PHPLib模板系统的详细用法请参考其帮助文档。
示例:
<?php
  include_once 'template.inc';
  $tpl = new Template();
  $tpl->set_root('views');

  if ($this->books)
  {
    $tpl->set_file(array(
        "booklist" => "booklist.tpl",
        "eachbook" => "eachbook.tpl",
    ));
    foreach ($this->books as $key => $val)
    {
      $tpl->set_var('author', $this->escape($val['author']));
      $tpl->set_var('title', $this->escape($val['title']));
      $tpl->parse("books", "eachbook", true);
    }
    $tpl->pparse("output", "booklist");
  }
  else
  {
    $tpl->setFile("nobooks", "nobooks.tpl");
    $tpl->pparse("output", "nobooks");
  }
?>
booklist.tpl文件内容:
<?php
  if ($this->books):
?>
  <table border=1>
  <tr>
    <th>作者</th>
    <th>书名</th>
  </tr>
  <?php
    foreach ($this->books as $key => $val):
  ?>
  <tr>
    <td><?php echo $this->escape($val['author']) ?></td>
    <td><?php echo $this->escape($val['title']) ?></td>
  </tr>
  <?php endforeach; ?>
  </table>
<?php
  else:
?>
  <p>There are no books to display.</p>
<?php
  endif;
eachbook.tpl文件内容:
<!-- eachbook.tpl -->
<tr>
  <td>{author}</td>
  <td>{title}</td>
</tr>

6.8视图脚本的模板系统—使用 Zend_View_Interface调用第三方模板引擎
我们还可以通过实现Zend_View_Interface接口,来得到一个可用的模板系统。
ZF对Zend_View_Interface接口的原始定义:
/** Return the actual template engine object */
public function getEngine();

/* Set the path to view scripts/templates */
public function setScriptPath($path);

/* Set a base path to all view resources */
public function setBasePath($path, $prefix = 'Zend_View');

/* Add an additional base path to view resources */
public function addBasePath($path, $prefix = 'Zend_View');

/* Retrieve the current script paths */
public function getScriptPaths();

/* Overloading methods for assigning template variables as object properties */
public function __set($key, $value);
public function __get($key);
public function __isset($key);
public function __unset($key);

/* Manual assignment of template variables, or ability to assign multiple
  variables en masse.*/
public function assign($spec, $value = null);

/* Unset all assigned template variables */
public function clearVars();

/* Render the template named $name */
public function render($name);
使用该接口,我们可以很容易的把第三方的模板引擎,比如Smarty,包装成Zend_View兼容的模板类。
6.8.1Smarty的安装
下载Smarty软件包,解压到ZEND的library文件夹下,就完成了安装。
为了在ZF的视图脚本里调用得到模板类文件,必须在引导文件Index.php的set_include_path部分添加Smarty模板类库文件夹Smarty-2.6.19/libs到搜索路径中,参看前面PHPlib的安装说明部分。
Smarty模板引擎需要建立template_dir和compile_dir文件夹才能工作。ZF手册里的示例因为缺少这些设置而无法运行,正确的代码片段如下:
    public function setScriptPath($path)
    {
        if (is_readable($path))
{
            $this->_smarty->template_dir = $path;
            $this->_smarty->compile_dir = $path;  //必须加语句:设置编译路径
            $this->_smarty->cache_dir = $path;    //设置缓存路径
return;
         }
……
我们把对Zend_View_Interface接口的实现的类,放在models文件夹下的ZendViewSmarty.php文件中,该文件的内容如下:
<?php
require_once 'Zend/View/Interface.php';
require_once 'Smarty.class.php';

class ZendViewSmarty implements Zend_View_Interface
{
    /**
     * Smarty object
     * @var Smarty
     */
    protected $_smarty;

    /**
     * Constructor
     * @param string $tmplPath
     * @param array $extraParams
     * @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 string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_smarty->template_dir = $path;
            $this->_smarty->compile_dir = $path;
            $this->_smarty->cache_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 string $path
     * @param string $prefix Unused
     * @return void
     */
    public function setBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * Alias for setScriptPath
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function addBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * Assign a variable to the template
     * @param string $key The variable name.
     * @param mixed $val The variable value.
     * @return void
     */
    public function __set($key, $val)
    {
        $this->_smarty->assign($key, $val);
    }

    /**
     * Retrieve an assigned variable
     * @param string $key 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 string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return (null !== $this->_smarty->get_template_vars($key));
    }

    /**
     * Allows unset() on object properties to work
     * @param string $key
     * @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 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)
    {
        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 string $name The template to process.
     * @return string The output.
     */
    public function render($name)
    {
        return $this->_smarty->fetch($name);
    }
}
?>
控制脚本中对我们我的模板类的调用代码:
   function smartyAction()
   {
      $view = new ZendViewSmarty(); //实例化新的模板类
      $view->setScriptPath('views'); //设置模板文件路径
      $view->book = 'Enter Zend Framework Programme'; //传递变量给模板引擎
      $view->author = '张庆(网眼)';
      echo $view->render('bookinfo.tpl'); //视图呈现
   }
我们看到,由于Smarty模板引擎的良好特性,除过实现上述接口的代码比较复杂以外,我们这里的控制代码要比应用PHPLib模板简单得多。我们的数据不必像PHPLib引擎那样,要把数据传给视图脚本,再由视图脚本声明PHPLib类,再把数据发送给模板去呈现。这里是在控制脚本里把数据直接传递给Smarty模板去呈现的。这是因为ZendViewSmarty实现的是Zend_View接口,它和Zend_View的用法是一样的。

注意:本例只是使用Smarty引擎的其中一种方法。在ZF中还可以用别的形式来使用Smarty模板引擎,我们会在别的章节里介绍。

抱歉!评论已关闭.