www.2527.com_澳门新葡8455手机版_新京葡娱乐场网址_
做最好的网站

用法详解,Framework教程之视图组件Zend_View用法详

2019-07-14 01:39 来源:未知

正文实例呈报了Zend Framework教程之视图组件Zend_View用法。分享给大家供大家参照他事他说加以考察,具体如下:

正文实例汇报了Zend Framework动作助手(Zend_Controller_Action_Helper)用法。分享给大家供大家仿效,具体如下:

本文实例呈报了Zend Framework实现Zend_View集成斯马特y模板系统的法子。分享给大家供大家参照他事他说加以考察,具体如下:

Zend_View是Zend Framework的视图组件,MVC中的视图层。 Zend_View也是选拔的间接对用户呈现的页面。这里介绍一下Zend_View的达成类,以及怎样和Controller结合在一块的。

由此助肢人体模型特式,能够把部分平常使用的功能模块做封装,进而在可以在急需的地点灵活运用,主假使在action使用。

Zend_View抽象出了Zend_View_Interface,能够让大家集成区别的视图化解方案,举个例子能够集成smarty。要在zend中央银行使另外视图系统作为视图,只要完成Zend_View_Interface接口就能够。

View的实现

Zend Framework中有二种帮手,动作助手(Zend_Controller_Action_Helper)和计算助手(Zend_View_Helper)。

Zend_View_Interface的接口定义:

Zend_View的实现重大是通过如下目录的类完毕:

动作助手得以向任何Zend_Controller_Action的衍生动作调节器中,即时的加盟功能(runtime and/or on-demand functionality),以使得增加公家的动作调整器成效时,尽量减弱衍生动作调节器类的必需。

<?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);
}

root@coder-671T-M:/library/Zend# tree | grep View.php
│   └── View/
├── View.php

动作帮手在须要调用时加载,能够在伸手的时候(bootstrap)大概动作调控器创造的时候(init())实例化。

集成Smarty的主干达成如下:

root@coder-671T-M:/library/Zend/View# tree
.
├── Abstract.php
├── Exception.php
├── Helper
│   ├── Abstract.php
│   ├── Action.php
│   ├── BaseUrl.php
│   ├── Currency.php
│   ├── Cycle.php
│   ├── DeclareVars.php
│   ├── Doctype.php
│   ├── Fieldset.php
│   ├── FormButton.php
│   ├── FormCheckbox.php
│   ├── FormElement.php
│   ├── FormErrors.php
│   ├── FormFile.php
│   ├── FormHidden.php
│   ├── FormImage.php
│   ├── FormLabel.php
│   ├── FormMultiCheckbox.php
│   ├── FormNote.php
│   ├── FormPassword.php
│   ├── Form.php
│   ├── FormRadio.php
│   ├── FormReset.php
│   ├── FormSelect.php
│   ├── FormSubmit.php
│   ├── FormTextarea.php
│   ├── FormText.php
│   ├── Gravatar.php
│   ├── HeadLink.php
│   ├── HeadMeta.php
│   ├── HeadScript.php
│   ├── HeadStyle.php
│   ├── HeadTitle.php
│   ├── HtmlElement.php
│   ├── HtmlFlash.php
│   ├── HtmlList.php
│   ├── HtmlObject.php
│   ├── HtmlPage.php
│   ├── HtmlQuicktime.php
│   ├── InlineScript.php
│   ├── Interface.php
│   ├── Json.php
│   ├── Layout.php
│   ├── Navigation
│   │   ├── Breadcrumbs.php
│   │   ├── HelperAbstract.php
│   │   ├── Helper.php
│   │   ├── Links.php
│   │   ├── Menu.php
│   │   └── Sitemap.php
│   ├── Navigation.php
│   ├── PaginationControl.php
│   ├── Partial
│   │   └── Exception.php
│   ├── PartialLoop.php
│   ├── Partial.php
│   ├── Placeholder
│   │   ├── Container
│   │   │   ├── Abstract.php
│   │   │   ├── Exception.php
│   │   │   └── Standalone.php
│   │   ├── Container.php
│   │   ├── Registry
│   │   │   └── Exception.php
│   │   └── Registry.php
│   ├── Placeholder.php
│   ├── RenderToPlaceholder.php
│   ├── ServerUrl.php
│   ├── TinySrc.php
│   ├── Translate.php
│   ├── Url.php
│   └── UserAgent.php
├── Interface.php
└── Stream.php

关系到的相关文书

smarty下载地址

6 directories, 70 files

在/library/Zend/Controller/Action/中

Zend_View和Zend_Controller的整合

│  Exception.php
│  HelperBroker.php
│  Interface.php

├─Helper
│  │  Abstract.php
│  │  ActionStack.php
│  │  AjaxContext.php
│  │  AutoCompleteDojo.php
│  │  AutoCompleteScriptaculous.php
│  │  Cache.php
│  │  ContextSwitch.php
│  │  FlashMessenger.php
│  │  Json.php
│  │  Redirector.php
│  │  Url.php
│  │  ViewRenderer.php
│  │
│  └─AutoComplete
│          Abstract.php

└─HelperBroker
       PriorityStack.php

目录结构

主要在Zend_Controller_Action类中,

广泛的动作帮手有

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

/**
   * Initialize View object
   *
   * Initializes {@link $view} if not otherwise a Zend_View_Interface.
   *
   * If {@link $view} is not otherwise set, instantiates a new Zend_View
   * object, using the 'views' subdirectory at the same level as the
   * controller directory for the current module as the base directory.
   * It uses this to set the following:
   * - script path = views/scripts/
   * - helper path = views/helpers/
   * - filter path = views/filters/
   *
   * @return Zend_View_Interface
   * @throws Zend_Controller_Exception if base view directory does not exist
   */
  public function initView()
  {
    if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
      return $this->view;
    }
    require_once 'Zend/View/Interface.php';
    if (isset($this->view) && ($this->view instanceof Zend_View_Interface)) {
      return $this->view;
    }
    $request = $this->getRequest();
    $module = $request->getModuleName();
    $dirs  = $this->getFrontController()->getControllerDirectory();
    if (empty($module) || !isset($dirs[$module])) {
      $module = $this->getFrontController()->getDispatcher()->getDefaultModule();
    }
    $baseDir = dirname($dirs[$module]) . DIRECTORY_SEPARATOR . 'views';
    if (!file_exists($baseDir) || !is_dir($baseDir)) {
      require_once 'Zend/Controller/Exception.php';
      throw new Zend_Controller_Exception('Missing base view directory ("' . $baseDir . '")');
    }
    require_once 'Zend/View.php';
    $this->view = new Zend_View(array('basePath' => $baseDir));
    return $this->view;
  }
  /**
   * Render a view
   *
   * Renders a view. By default, views are found in the view script path as
   * <controller>/<action>.phtml. You may change the script suffix by
   * resetting {@link $viewSuffix}. You may omit the controller directory
   * prefix by specifying boolean true for $noController.
   *
   * By default, the rendered contents are appended to the response. You may
   * specify the named body content segment to set by specifying a $name.
   *
   * @see Zend_Controller_Response_Abstract::appendBody()
   * @param string|null $action Defaults to action registered in request object
   * @param string|null $name Response object named path segment to use; defaults to null
   * @param bool $noController Defaults to false; i.e. use controller name as subdir in which to search for view script
   * @return void
   */
  public function render($action = null, $name = null, $noController = false)
  {
    if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
      return $this->_helper->viewRenderer->render($action, $name, $noController);
    }
    $view  = $this->initView();
    $script = $this->getViewScript($action, $noController);
    $this->getResponse()->appendBody(
      $view->render($script),
      $name
    );
  }
  /**
   * Render a given view script
   *
   * Similar to {@link render()}, this method renders a view script. Unlike render(),
   * however, it does not autodetermine the view script via {@link getViewScript()},
   * but instead renders the script passed to it. Use this if you know the
   * exact view script name and path you wish to use, or if using paths that do not
   * conform to the spec defined with getViewScript().
   *
   * By default, the rendered contents are appended to the response. You may
   * specify the named body content segment to set by specifying a $name.
   *
   * @param string $script
   * @param string $name
   * @return void
   */
  public function renderScript($script, $name = null)
  {
    if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
      return $this->_helper->viewRenderer->renderScript($script, $name);
    }
    $view = $this->initView();
    $this->getResponse()->appendBody(
      $view->render($script),
      $name
    );
  }

FlashMessenger 用来管理Flash Messenger会话;
Json 用来解码和出殡和埋葬 JSON 响应;
Url  用于成立Urls;
Redirector 提供另一种达成格局,帮忙程序重定向到中间依旧外界页面;
ViewRenderer 自动的成就在调节器内创立视图对象并渲染视图的长河;
AutoComplete 自动响应 AJAX 的自发性达成;
ContextSwitch 和 AjaxContext 为你的动作提供代替响应格式;
Cache  实现cache的有关操作;
ActionStack 用于操作动作酒馆。

24 directories, 134 files

Zend_View.php类

动手的二种实例化使用格局

/zf_demo1/library/Lq/View/Smarty.php

<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @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
 * @version  $Id: View.php 23775 2011-03-01 17:25:24Z ralph $
 */
/**
 * Abstract master class for extension.
 */
require_once 'Zend/View/Abstract.php';
/**
 * Concrete class for handling view scripts.
 *
 * @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
 */
class Zend_View extends Zend_View_Abstract
{
  /**
   * Whether or not to use streams to mimic short tags
   * @var bool
   */
  private $_useViewStream = false;
  /**
   * Whether or not to use stream wrapper if short_open_tag is false
   * @var bool
   */
  private $_useStreamWrapper = false;
  /**
   * Constructor
   *
   * Register Zend_View_Stream stream wrapper if short tags are disabled.
   *
   * @param array $config
   * @return void
   */
  public function __construct($config = array())
  {
    $this->_useViewStream = (bool) ini_get('short_open_tag') ? false : true;
    if ($this->_useViewStream) {
      if (!in_array('zend.view', stream_get_wrappers())) {
        require_once 'Zend/View/Stream.php';
        stream_wrapper_register('zend.view', 'Zend_View_Stream');
      }
    }
    if (array_key_exists('useStreamWrapper', $config)) {
      $this->setUseStreamWrapper($config['useStreamWrapper']);
    }
    parent::__construct($config);
  }
  /**
   * Set flag indicating if stream wrapper should be used if short_open_tag is off
   *
   * @param bool $flag
   * @return Zend_View
   */
  public function setUseStreamWrapper($flag)
  {
    $this->_useStreamWrapper = (bool) $flag;
    return $this;
  }
  /**
   * Should the stream wrapper be used if short_open_tag is off?
   *
   * @return bool
   */
  public function useStreamWrapper()
  {
    return $this->_useStreamWrapper;
  }
  /**
   * Includes the view script in a scope with only public $this variables.
   *
   * @param string The view script to execute.
   */
  protected function _run()
  {
    if ($this->_useViewStream && $this->useStreamWrapper()) {
      include 'zend.view://' . func_get_arg(0);
    } else {
      include func_get_arg(0);
    }
  }
}

1.通过Zend_Controller_Action的 $_helper成员的getHelper()方法。直接调用getHelper(),传入助手的称号就可以。

<?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);
  }
}

私下认可情状会自行通过Controller会通过render方法来实例化Zend_View, 然后rener到相应的视图文件中。当然能够本人实例化Zend_View,然后采纳。

$redirector = $this->_helper->getHelper('Redirector');
//$redirector->getName();
$redirector->gotoSimple('index2');

/zf_demo1/application/configs/application.ini

action默认指向的文件是和action的称号一致,假诺要钦命视图文件,能够透过$this->render的连带办法钦点.也足以因而addScriptPath和setScriptPath设置视图像和文字件的目录。

2.直接通过会见的_helper帮手的性能对应的副手对象。

[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

例如

$redirector = $this->_helper->Redirector;

/zf_demo1/application/Bootstrap.php

$view = new Zend_View();
$view->addScriptPath('/www/app/myviews');
$view->addScriptPath('/www/app/viewscomm');
// 如果调用 $view->render('example.php'), Zend_View 将
// 首先查找 "/www/app/myviews/example.php", 找不到再找"/www/app/viewscomm/example.php", 如果还找不到,最后查找当前目录下/的"example.php".

Zend_Controller_Action_HelperBroker

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

Zend_View的常用方法

中文名称译作"帮手经纪人",循名责实,是动作助手的中间人。

/zf_demo1/application/controllers/IndexController.php

public function __construct($config = array())

在动作的实例化使用的章程的第三种办法正是经过Zend_Controller_Action_HelperBroker的魔术点子__get()来贯彻的。

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

例如

Zend_Controller_Action_HelperBroker的完成以及常用方法列表

<!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>
array(
 'escape' => array(),
 'encoding' => array(),
);
<?php
/**
 * @see Zend_Controller_Action_HelperBroker_PriorityStack
 */
require_once 'Zend/Controller/Action/HelperBroker/PriorityStack.php';
/**
 * @see Zend_Loader
 */
require_once 'Zend/Loader.php';
/**
 * @category  Zend
 * @package  Zend_Controller
 * @subpackage Zend_Controller_Action
 * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   New BSD License
 */
class Zend_Controller_Action_HelperBroker
{
  /**
   * $_actionController - ActionController reference
   *
   * @var Zend_Controller_Action
   */
  protected $_actionController;
  /**
   * @var Zend_Loader_PluginLoader_Interface
   */
  protected static $_pluginLoader;
  /**
   * $_helpers - Helper array
   *
   * @var Zend_Controller_Action_HelperBroker_PriorityStack
   */
  protected static $_stack = null;
  /**
   * Set PluginLoader for use with broker
   *
   * @param Zend_Loader_PluginLoader_Interface $loader
   * @return void
   */
  public static function setPluginLoader($loader)
  {
    if ((null !== $loader) && (!$loader instanceof Zend_Loader_PluginLoader_Interface)) {
      require_once 'Zend/Controller/Action/Exception.php';
      throw new Zend_Controller_Action_Exception('Invalid plugin loader provided to HelperBroker');
    }
    self::$_pluginLoader = $loader;
  }
  /**
   * Retrieve PluginLoader
   *
   * @return Zend_Loader_PluginLoader
   */
  public static function getPluginLoader()
  {
    if (null === self::$_pluginLoader) {
      require_once 'Zend/Loader/PluginLoader.php';
      self::$_pluginLoader = new Zend_Loader_PluginLoader(array(
        'Zend_Controller_Action_Helper' => 'Zend/Controller/Action/Helper/',
      ));
    }
    return self::$_pluginLoader;
  }
  /**
   * addPrefix() - Add repository of helpers by prefix
   *
   * @param string $prefix
   */
  static public function addPrefix($prefix)
  {
    $prefix = rtrim($prefix, '_');
    $path  = str_replace('_', DIRECTORY_SEPARATOR, $prefix);
    self::getPluginLoader()->addPrefixPath($prefix, $path);
  }
  /**
   * addPath() - Add path to repositories where Action_Helpers could be found.
   *
   * @param string $path
   * @param string $prefix Optional; defaults to 'Zend_Controller_Action_Helper'
   * @return void
   */
  static public function addPath($path, $prefix = 'Zend_Controller_Action_Helper')
  {
    self::getPluginLoader()->addPrefixPath($prefix, $path);
  }
  /**
   * addHelper() - Add helper objects
   *
   * @param Zend_Controller_Action_Helper_Abstract $helper
   * @return void
   */
  static public function addHelper(Zend_Controller_Action_Helper_Abstract $helper)
  {
    self::getStack()->push($helper);
    return;
  }
  /**
   * resetHelpers()
   *
   * @return void
   */
  static public function resetHelpers()
  {
    self::$_stack = null;
    return;
  }
  /**
   * Retrieve or initialize a helper statically
   *
   * Retrieves a helper object statically, loading on-demand if the helper
   * does not already exist in the stack. Always returns a helper, unless
   * the helper class cannot be found.
   *
   * @param string $name
   * @return Zend_Controller_Action_Helper_Abstract
   */
  public static function getStaticHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    $stack = self::getStack();
    if (!isset($stack->{$name})) {
      self::_loadHelper($name);
    }
    return $stack->{$name};
  }
  /**
   * getExistingHelper() - get helper by name
   *
   * Static method to retrieve helper object. Only retrieves helpers already
   * initialized with the broker (either via addHelper() or on-demand loading
   * via getHelper()).
   *
   * Throws an exception if the referenced helper does not exist in the
   * stack; use {@link hasHelper()} to check if the helper is registered
   * prior to retrieving it.
   *
   * @param string $name
   * @return Zend_Controller_Action_Helper_Abstract
   * @throws Zend_Controller_Action_Exception
   */
  public static function getExistingHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    $stack = self::getStack();
    if (!isset($stack->{$name})) {
      require_once 'Zend/Controller/Action/Exception.php';
      throw new Zend_Controller_Action_Exception('Action helper "' . $name . '" has not been registered with the helper broker');
    }
    return $stack->{$name};
  }
  /**
   * Return all registered helpers as helper => object pairs
   *
   * @return array
   */
  public static function getExistingHelpers()
  {
    return self::getStack()->getHelpersByName();
  }
  /**
   * Is a particular helper loaded in the broker?
   *
   * @param string $name
   * @return boolean
   */
  public static function hasHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    return isset(self::getStack()->{$name});
  }
  /**
   * Remove a particular helper from the broker
   *
   * @param string $name
   * @return boolean
   */
  public static function removeHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    $stack = self::getStack();
    if (isset($stack->{$name})) {
      unset($stack->{$name});
    }
    return false;
  }
  /**
   * Lazy load the priority stack and return it
   *
   * @return Zend_Controller_Action_HelperBroker_PriorityStack
   */
  public static function getStack()
  {
    if (self::$_stack == null) {
      self::$_stack = new Zend_Controller_Action_HelperBroker_PriorityStack();
    }
    return self::$_stack;
  }
  /**
   * Constructor
   *
   * @param Zend_Controller_Action $actionController
   * @return void
   */
  public function __construct(Zend_Controller_Action $actionController)
  {
    $this->_actionController = $actionController;
    foreach (self::getStack() as $helper) {
      $helper->setActionController($actionController);
      $helper->init();
    }
  }
  /**
   * notifyPreDispatch() - called by action controller dispatch method
   *
   * @return void
   */
  public function notifyPreDispatch()
  {
    foreach (self::getStack() as $helper) {
      $helper->preDispatch();
    }
  }
  /**
   * notifyPostDispatch() - called by action controller dispatch method
   *
   * @return void
   */
  public function notifyPostDispatch()
  {
    foreach (self::getStack() as $helper) {
      $helper->postDispatch();
    }
  }
  /**
   * getHelper() - get helper by name
   *
   * @param string $name
   * @return Zend_Controller_Action_Helper_Abstract
   */
  public function getHelper($name)
  {
    $name = self::_normalizeHelperName($name);
    $stack = self::getStack();
    if (!isset($stack->{$name})) {
      self::_loadHelper($name);
    }
    $helper = $stack->{$name};
    $initialize = false;
    if (null === ($actionController = $helper->getActionController())) {
      $initialize = true;
    } elseif ($actionController !== $this->_actionController) {
      $initialize = true;
    }
    if ($initialize) {
      $helper->setActionController($this->_actionController)
          ->init();
    }
    return $helper;
  }
  /**
   * Method overloading
   *
   * @param string $method
   * @param array $args
   * @return mixed
   * @throws Zend_Controller_Action_Exception if helper does not have a direct() method
   */
  public function __call($method, $args)
  {
    $helper = $this->getHelper($method);
    if (!method_exists($helper, 'direct')) {
      require_once 'Zend/Controller/Action/Exception.php';
      throw new Zend_Controller_Action_Exception('Helper "' . $method . '" does not support overloading via direct()');
    }
    return call_user_func_array(array($helper, 'direct'), $args);
  }
  /**
   * Retrieve helper by name as object property
   *
   * @param string $name
   * @return Zend_Controller_Action_Helper_Abstract
   */
  public function __get($name)
  {
    return $this->getHelper($name);
  }
  /**
   * Normalize helper name for lookups
   *
   * @param string $name
   * @return string
   */
  protected static function _normalizeHelperName($name)
  {
    if (strpos($name, '_') !== false) {
      $name = str_replace(' ', '', ucwords(str_replace('_', ' ', $name)));
    }
    return ucfirst($name);
  }
  /**
   * Load a helper
   *
   * @param string $name
   * @return void
   */
  protected static function _loadHelper($name)
  {
    try {
      $class = self::getPluginLoader()->load($name);
    } catch (Zend_Loader_PluginLoader_Exception $e) {
      require_once 'Zend/Controller/Action/Exception.php';
      throw new Zend_Controller_Action_Exception('Action Helper by name ' . $name . ' not found', 0, $e);
    }
    $helper = new $class();
    if (!$helper instanceof Zend_Controller_Action_Helper_Abstract) {
      require_once 'Zend/Controller/Action/Exception.php';
      throw new Zend_Controller_Action_Exception('Helper name ' . $name . ' -> class ' . $class . ' is not of type Zend_Controller_Action_Helper_Abstract');
    }
    self::getStack()->push($helper);
  }
}

假使急需配置smarty能够张开/zf_demo1/library/smartylib/斯马特y.class.php文件实行相应布署举个例子

常见key:

助手经纪人的宽泛用法:

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

escape、encoding、basePath、basePathPrefix、scriptPath、helperPath、 helperPathPrefix、filterPath、filterPathPrefix、filter
public function getEngine() Return the template engine object

一、注册三个动手

越多关于zend相关内容感兴趣的读者可查看本站专项论题:《Zend FrameWork框架入门教程》、《php非凡开辟框架总括》、《Yii框架入门及常用技能计算》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php mysql数据库操作入门教程》及《php常见数据库操作本领汇总》

public function init()起首化函数

1.

梦想本文所述对我们PHP程序设计有着支持。

/**
* Given a base path, sets the script, helper, and filter paths relative to it
*
* Assumes a directory structure of:
* <code>
* basePath/
*   scripts/
*   helpers/
*   filters/
* </code>
*
* @param string $path
* @param string $prefix Prefix to use for helper and filter paths
* @return Zend_View_Abstract
*/
public function setBasePath($path, $classPrefix = 'Zend_View')
/**
* Given a base path, add script, helper, and filter paths relative to it
*
* Assumes a directory structure of:
* <code>
* basePath/
*   scripts/
*   helpers/
*   filters/
* </code>
*
* @param string $path
* @param string $prefix Prefix to use for helper and filter paths
* @return Zend_View_Abstract
*/
public function addBasePath($path, $classPrefix = 'Zend_View')
public function addScriptPath($path)Adds to the stack of view script paths in LIFO order.
public function setScriptPath($path) Resets the stack of view script paths.
public function getScriptPath($name)Return full path to a view script specified by $name
public function getScriptPaths()Returns an array of all currently set script paths
public function addHelperPath($path, $classPrefix = 'Zend_View_Helper_')Adds to the stack of helper paths in LIFO order.
public function setHelperPath($path, $classPrefix = 'Zend_View_Helper_')Resets the stack of helper paths.
public function getHelperPath($name) Get full path to a helper class file specified by $name
public function getHelperPaths()Returns an array of all currently set helper paths
public function getHelper($name) Get a helper by name
public function getHelpers()Get array of all active helpers
public function getAllPaths() Return associative array of path types => paths
public function setEscape($spec)
/**
* Assigns variables to the view script via differing strategies.
*
* Zend_View::assign('name', $value) assigns a variable called 'name'
* with the corresponding $value.
*
* Zend_View::assign($array) assigns the array keys as variable
* names (with the corresponding array values).
*
* @see  __set()
* @param string|array The assignment strategy to use.
* @param mixed (Optional) If assigning a named variable, use this
* as the value.
* @return Zend_View_Abstract Fluent interface
* @throws Zend_View_Exception if $spec is neither a string nor an array,
* or if an attempt to set a private or protected member is detected
*/
public function assign($spec, $value = null)
Zend_Controller_Action_HelperBroker::addHelper($helper);

你可能感兴趣的篇章:

  • Zend Framework教程之视图组件Zend_View用法详解
  • Zend Framework管理Json数据格局详解
  • Zend Framework使用Zend_Loader组件动态加载文件和类用法详解
  • Zend Framework入门教程之Zend_Registry组件用法详解
  • Zend Framework入门教程之Zend_Config组件用法详解
  • Zend Framework过滤器Zend_Filter用法详解
  • Zend Framework达成自定义过滤器的点子
  • php入门教程之Zend Studio设置与开垦实例
  • Zend Framework开采入门非凡教程
  • Zend Framework入门教程之Zend_View组件用法示例

在controller的action可以经过assign传递参数到视图脚本。

2.通过addPrefix()方法包括三个类前缀参数,用来参与动和自动定义助手类的渠道。
务求前缀遵从Zend Framework的类命名惯例。

例如

// Add helpers prefixed with My_Action_Helpers in My/Action/Helpers/
Zend_Controller_Action_HelperBroker::addPrefix('My_Action_Helpers');
$this->view->assign('roles', $roles);
$this->view->assign('num', $num);
$this->view->assign('a', $a);

3.运用addPath()方法第三个参数为三个目录,第三个为类前缀(默感觉'Zend_Controller_Action_Helper')。

依然也足以用

用来将团结的类前缀映射到内定的目录。

$this->view->roles=$roles;
$this->view->a=$a;
public function render($name) Processes a view script and returns the output.
public function escape($var):Escapes a value for output in a view script.
public function setEncoding($encoding) Set encoding to use with htmlentities() and htmlspecialchars()
public function getEncoding() :Return current escape encoding
// Add helpers prefixed with Helper in Plugins/Helpers/
Zend_Controller_Action_HelperBroker::addPath('./Plugins/Helpers',
                       'Helper');

视图脚本文件中的常见用法

二、判读帮手是或不是留存

收获传递过来的值

利用hasHelper($name)方法来剖断助手经纪人中是不是留存某出手,$name是帮手的短名称(去掉前缀的):

$this->roles
// Check if 'redirector' helper is registered with the broker:
if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) {
  echo 'Redirector helper registered';
}

动用部分遍布的助理员方法:

从帮手经纪人中收获帮手有八个静态方法:getExistingHelper() 和 getStaticHelper() 。getExistingHelper()将获得帮手仅当它原先调用过大概显性地通过帮手经纪人注册过,不然就抛出一个十二分。getStaticHelper() 的做法和getExistingHelper()一样,但只要还未曾挂号帮手旅社,它将尝试开始化助手,为获得你要配置的的臂膀,getStaticHelper()是贰个好的选取。

$this->baseUrl();
$this->url();
$this->paginationControl();
$this->partial()

四个措施都带二个参数,$name,它是帮手的短名称(去掉前缀)。

视图常见用法举个例子

// Check if 'redirector' helper is registered with the broker, and fetch:
if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) {
  $redirector =
    Zend_Controller_Action_HelperBroker::getExistingHelper('redirector');
}
// Or, simply retrieve it, not worrying about whether or not it was
// previously registered:
$redirector =
  Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
}

在bootstrap初始化view或者controller的init文件中

三、removeHelper($name)删除帮手经纪人中的某些帮手,$name是助手的短名称。

/**
 * Initialize the common view helper
 */
protected function _initViewHelper()
{
  $boot=$this->bootstrap('View');
  $view = $boot->getResource('View');
        $view->setHelperPath('Sql/View/Helper', 'Sql_View_Helper');
}
// Conditionally remove the 'redirector' helper from the broker:
if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) {
  Zend_Controller_Action_HelperBroker::removeHelper('redirector')
}

action中

更加多关于zend相关内容感兴趣的读者可查阅本站专项论题:《Zend FrameWork框架入门教程》、《php卓绝开采框架总括》、《Yii框架入门及常用本领总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php mysql数据库操作入门教程》及《php常见数据库操作手艺汇总》

/**
 *
 * @return void
 */
public function listAction()
{
  $this->view->assign('data', $data);
}

瞩望本文所述对我们PHP程序设计有着帮助。

视图像和文字件

你可能感兴趣的文章:

  • Zend Framework教程之Zend_Helpers动作助手ViewRenderer用法详解
  • Zend Framework教程之动作的基类Zend_Controller_Action详解
  • Zend Framework动作帮手Redirector用法实例详解
  • Zend Framework动作帮手Url用法详解
  • Zend Framework动作帮手Json用法实例剖判
  • Zend Framework动作助手FlashMessenger用法详解
  • Zend Framework创立和睦的动作帮手详解
  • Zend Framework教程在此以前端调节器Zend_Controller_Front用法详解
  • php入门教程之Zend Studio设置与开辟实例
  • Zend Framework开辟入门突出教程
  • Zend Framework动作调控器用法示例

list.phtml

<?php foreach ($this->data as $item) : ?>
<tr style="height: 19px;">
    <td class="datagrid-cell"><?php echo($item->item1);?></td>
</tr>
<?php endforeach; ?>

更加多关于zend相关内容感兴趣的读者可查阅本站专项论题:《Zend FrameWork框架入门教程》、《php卓越开辟框架总括》、《Yii框架入门及常用技术总计》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php mysql数据库操作入门教程》及《php常见数据库操作本事汇总》

盼望本文所述对我们PHP程序设计有着帮衬。

你或者感兴趣的篇章:

  • Zend Framework实现Zend_View集成Smarty模板系统的议程
  • Zend Framework管理Json数据情势详解
  • Zend Framework使用Zend_Loader组件动态加载文件和类用法详解
  • Zend Framework入门教程之Zend_Registry组件用法详解
  • Zend Framework入门教程之Zend_Config组件用法详解
  • Zend Framework过滤器Zend_Filter用法详解
  • Zend Framework达成自定义过滤器的不二秘诀
  • php入门教程之Zend Studio设置与费用实例
  • Zend Framework开拓入门卓越教程
  • Zend Framework入门教程之Zend_View组件用法示例
TAG标签:
版权声明:本文由澳门新葡8455手机版发布于计算机编程,转载请注明出处:用法详解,Framework教程之视图组件Zend_View用法详