Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^226) CHAPTER 15 ■ INTRODUCTION TO THE ZEND FRAMEWORK
The Response Object
The response object contains methods that allow you to set headers and assign response bodies.
Listing 15-9 demonstrates both setting a Content-Type header and assigning a request body in
the context of a JavaScript Object Notation (JSON) serving action.
Listing 15-9. A JSON Returning Action
public function jsonAction() {
//Don't render a template
$this->getHelper('ViewRenderer')->setNoRender();
//Set content type headers in the response object
$this->getResponse()->setHeader('Content-Type', 'application/json');
//Manually assign the response body, instead of rendering a template
$json = '{"Name":"Kevin"}';
$this->getResponse()->setBody($json);
}
Additionally, you might use setHttpResponseCode() to set the status code, such as when
you want to create a 404 or 503 error page.


Using Built-in Action Helpers.


Action helpers are reusable classes that add functionality to the controller—typically, function-
ality that would not be considered program logic. For example, the ability to redirect the user
to another page is implemented as a helper in the Zend Framework.
You will learn how to create your own action helpers in Chapter 17. Here, let’s look at a
couple of the built-in action helpers.

The Redirector Helper
The Redirector helper does what its name implies: it allows you to redirect the user to a new
page. It provides several methods, but the key one is goto().

void goto($action, $controller=null, $module=null, $params=array())

The goto() method performs the redirection and allows you to redirect to a specific action.
The API provided is more desirable than using headers directly, as there are several factors that
can affect a Zend Framework application’s URL layout down the road.
To redirect a user to a new page, add an action method to your customers controller, as
shown in Listing 15-10.

Listing 15-10. Using the Redirector Helper (in CustomersController.php)

public function redirectAction() {
$this->getHelper('redirector')->goto('index');
}

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

Free download pdf