Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^220) CHAPTER 15 ■ INTRODUCTION TO THE ZEND FRAMEWORK
is indexAction. The default controller file is named IndexController.php and should be placed
within your application/controllers directory. Listing 15-2 shows your default controller,
which should become /application/controllers/IndexController.php.
Listing 15-2. The Default Controller (application/controllers/IndexController.php)
<?php
class IndexController extends Zend_Controller_Action {
public function indexAction() {
}
}
With your index controller created, your site should now show another exception.
'script 'index/index.phtml' not found in path
This is because you have no view defined for the index controller’s index action.


Adding a View.


In the previous chapter, you manually rendered your views by creating a view object, assigning
variables, and calling a render() method. The Zend Framework has a default component called the
view renderer, which handles two of these steps for you: automatically creating a view instance
and rendering a view script. The view instance is stored in the controller instance as $this->view.
For your application, your first view template will be application/views/scripts/index/
index.phtml, as shown in Listing 15-3. The directory index refers to the controller name, and
the index.phtml file refers to the method name without the Action suffix.

Listing 15-3. A Sample View (application/views/scripts/index/index.phtml)

<html>
<body>
<p>Welcome: <?php echo $this->name; ?></p>
</body>
</html>

That’s simple enough. Now, to use it, you need to refactor your indexAction method in
IndexController.php and set the name variable, as shown in Listing 15-4.

Listing 15-4. A View-Enabled Action (in IndexController.php)

public function indexAction() {
$this->view->name = 'Kevin';
}

If you reload your page, you should see “Welcome: Kevin.” You now have a working Zend
Framework application!

McArthur_819-9C15.fm Page 220 Thursday, February 28, 2008 7:44 AM

Free download pdf