Access views in Models/Controllers

2019-02-20 02:50发布

问题:

I have a class MyData.php like this:

class myData {
  function render() {
    $view = new Zend_View();
    $view->str = 'This is string.';
    echo $view->render('myview.phtml');
  }
}

and a myview.phtml file:

<div id='someid'><?= $this->str ?></div>

In another view I am doing something like this:

<?php
    $obj = new myData ();
    $obj->render(); // it should be <div id='someid'>This is string.</div>
?>

It is giving me following exception:

Message: no view script directory set; unable to determine location for view script

MyData.php and myview.phtml are in same directory.

回答1:

You are creating a new Zend_View instance. You should not do this. To get the existing view instance you could do as follows:

$view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');

Also, I think that the view script path should be relative to APPLICATION_PATH/views/scripts folder.



回答2:

I did it like this:

I changed my myview.phtml to myview.php

<div id='someid'><?= $this->str ?></div>

In myData class render function:

class myData {
  function render() {
    $view = new Zend_View();
    $view->setScriptPath( "/Directory/Path/For/myview/php/file" );
    $view->str = 'This is string.';
    echo $view->render('myview.php');
  }
}

And all things are working as I asked in question. I was missing $view->setScriptPath($path); in my code.

Help:

  • http://framework.zend.com/manual/en/zend.view.scripts.html
  • http://forums.zend.com/viewtopic.php?f=69&t=3966#p15370
  • http://framework.zend.com/issues/browse/ZF-2353


回答3:

If you are usin the full MVC stack its youre better off just creating a view helper for this type of thing... or simply passing the using the Partial view helper and passing your object to it.

For example with the exisiting Zend_View_Helper_Partial....

in your controller create the myData object and assign it to the view:

public function indexAction()
{
   $this->view->mydata = new MyData();
}

in the view for the action:

echo $this->partial('myview.phtml', array('obj' => $this->mydata));

Then in your myview.phtml you can do:

<div><?php echo $this->obj->somevar ?></div>

For your example it looks like you dont even need the myData object at all you can just assign the str variable to the view and pass it along to the partial instead of creating an object.

You should read the Zend_View docs...