Question

I have a project, it has a structure like this:

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

I want to make a variable like the following

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

and it can be used in many views, in many modules. I think I can do it by declaring the variable in Bootstrap.php (application) but I don't know how to do that.

Was it helpful?

Solution

Usually, I just place myself such variables into application bootstrap file. Here's an example:

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

    }

}

I hope it helps!

OTHER TIPS

Base Url is available after routing has been completed (routeShutdown hook) so accessing it in Bootstrap will not work .

So create a controller plugin inside preDispatch() do

public function preDispatch($req) {

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

}

To access it inside view do like index.phtml

 echo $this->placeholder('burl'); 

You could use the Zend_Registry.

In your bootstrap or wherever in your site just State

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

To use in a view just

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

for extra credit you could also make a view helper for this (there is one with ZF2)

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

In your bootstrap you will add a method like:

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

Also if you are using the view helper approach you will also want to register the helper path.. you can do this in _initView in the bootstrap.

    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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top