Sunday 27 September 2009

Zend Framework View not found

I was messing about with a new installation of the Zend Framework on my system after reading through the basic tutorials on the web (the official ZF website tutorial is horrible) and I came across something that didn't work when using Views.

Here is the typical usage as shown in a tutorial on the IBM site (tut 2 [sign in required]):

<?php
//You should have require_once 'Zend/Loader.php'; in your bootstrap (index.php)

Zend::loadClass('Zend_Controller_Action');
Zend::loadClass('Zend_View');

class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$view = new Zend_View();
setScriptPath('views'); //the offending line
echo $view->render('indexIndexView.php');
}
}
?>

This is a typical controller class that makes a View object in order to render the HTML in the indexIndxView.php file to your browser. What should happen is that the contents of indexIndexView.php are displayed on your webpage. What actually happens is you get this error:

An error occurred

Application error

Exception information:

Message: script 'indexIndexView.php' not found in path (views\)

And then it outputs the stack trace and other stuff.

Evidently, this is a path problem - it doesn't know where to look for the files. Believe it or not, Zend didn't make their scripts auto-discover the location of the views folder! The thing is, the people who write the software and these tutorials should really mention these errors and how to get past them because it's things like this that put people off learning frameworks in the first place because the simplest things don't even work. Trying to Google this error is next to useless as it's really difficult to find the solution.

The fix is actually really easy:

$view->setScriptPath(APPLICATION_PATH . '/views/');

The APPLICATION_PATH is a constant set in the bootstrap file that can be used to make sure your files gets found. Why do people negelect to mention such important things?

Anyway, seeing the inadequecy of needing to create a view object and set its script path in every controller method, I decided to just create an instance of the view object in the bootstrap (index.php):

Zend_Loader::loadClass('Zend_View');
$view = new Zend_View();
$view->setScriptPath(APPLICATION_PATH . '/views/');

Then in every controller method I need to render a view in I just write this code (without the silly file naming OC):

global $view;
echo $view->render('indexIndexView.php');

No comments:

Post a Comment