0

我有一个项目,它的结构如下:

http://img526.imageshack.us/img526/2333/92348689.png

我想制作一个如下所示的变量

$templatePath = $this->baseUrl('/application/templates/')` 

它可以在许多视图、许多模块中使用。我想我可以通过在Bootstrap.php(应用程序)中声明变量来做到这一点,但我不知道该怎么做。

4

3 回答 3

2

通常,我只是将这些变量放入应用程序引导文件中。这是一个例子:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

    protected function _initViewVariables() {
        $this->bootstrap('View');

        $this->view->fooValue = 'foo';
        $this->view->barValue = 'bar';

        $config = Zend_Registry::get('config');

        if( $config->recaptcha->enabled ) {
            $this->view->captcha = true;
            $this->view->recaptchaPublicKey = $config->recaptcha->publicKey;
        }
        else {
            $this->view->captcha = false;
        }

    }

}

我希望它有帮助!

于 2013-06-08T21:29:37.163 回答
1

Base Url 在路由完成后可用(routeShutdown 挂钩),因此无法在 Bootstrap 中访问它。

所以在 preDispatch() 中创建一个控制器插件

public function preDispatch($req) {

$view = new Zend_View();
$view->placeholder('burl')->set(Zend_Controller_Front::getInstance()->getBaseUrl());

}

要在视图中访问它,请执行 index.phtml

 echo $this->placeholder('burl'); 
于 2013-06-08T03:40:02.423 回答
0

您可以使用 Zend_Registry。

在您的引导程序或您网站中的任何地方,只需声明

 Zend_Registry::set("TagLine", "Have a Nice Day");

在视图中使用

 <?= Zend_Registry::get("TagLine"); ?>

为了获得额外的功劳,您还可以为此制作一个视图助手(ZF2 有一个)

class My_View_Helper_Registry extends Zend_View_Helper_Abstract
{
    public function registry($key)
    {
        return Zend_Registry::get($key);
    }
}

在您的引导程序中,您将添加一个方法,例如:

protected function _initSiteRegistry(){
    Zend_Registry::set("Site_Name", "My Cool Site";
    Zend_Registry::set("Site_TagLine", "Have a nice day";
}

此外,如果您使用视图助手方法,您还需要注册助手路径。您可以在引导程序的 _initView 中执行此操作。

    protected function _initView(){
            $view = new Zend_View();
            $view->doctype("HTML5");
            $view->setEncoding("UTF-8");
            $view->addScriptPath(APPLICATION_PATH."/local/views");
            // set this as the viewRenderer's view. 
            $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
        $viewRenderer->setView($view);
            $view->addHelperPath("My/View/Helper/", "My_View_Helper_");
            return $view;
    }
于 2013-06-07T16:13:46.520 回答