This book is a collection of articles related to the Zend Framework.
Zend Framework users know that Dojo toolkit is integrated to 1.6+ release. In the previous post I demonstrated how to add a cool Dojo date picker widget to your text input form element by manually typing the JavaScript code. In this post let us discover how to create a cool date picker form element with Zend_Dojo. As the title says you don't have to write a single line of JavaScript. Zend_Dojo does all the work for you.
Prerequisite: you are familiar with Zend_Form, Zend_Controller and Zend_Layout.
Bootstrap: Zend Framework comes with many Dojo specific view helpers. You have to instruct the view object to find Dojo view helpers.
Grab the view object and add the following line in your bootstrap file.
<?php
// Create new view object if not already instantiated
//$view = new Zend_View();
Zend_Dojo::enableView($view);
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->setView($view);
?>
This sets up the Dojo environment and uses AOL CDN by default. This is a one time configuration for your application. You can make use of dojo view helper methods available to specify whether to use a CDN or a local path to a Dojo install, paths to custom Dojo modules, dojo.require statements, dijit stylesheet themes to use and to create dojo.addOnLoad() events.
Creating the form:
<?php
$form = new Zend_Form;
$name = $form->createElement('text', 'name')
->setLabel('Your full name')
->setRequired(true);
?>
Let us call our date picker element 'birthday'. We make use of the DateTextBox Dojo widget in this example.
<?php
$birthday = new Zend_Dojo_Form_Element_DateTextBox('birthday');
$birthday->setLabel('Birthday');
?>
<!-- indicative output --> <input type="text" name="date" dojoType="dijit.form.DateTextBox" />
Create a submit element and add the elements to the form.
<?php
$submit = $form->createElement('submit', 'submit');
$form->addElements(array($name, $birthday, $submit));
?>
We are done with creating the form. I have posted the complete controller code below which has a function to create the form.
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
// Call the getForm function
$form = $this->getForm();
if ($this->_request->isPost()) {
if ($form->isValid($_POST)) {
// Process data
// Pass the name and birthday values to the view so that
// You can display them in the view
$this->view->name = $this->_getParam('name');
$this->view->birthday = $this->_getParam('birthday');
} else {
//If form validation fails populate and display the form again
$form->populate($_POST);
$this->view->form = $form;
}
} else {
//If the request is not post display the form
$this->view->form = $form;
}
}
// Function to create the form
public function getForm()
{
$form = new Zend_Form;
$name = $form->createElement('text', 'name')
->setLabel('Your full name')
->setRequired(true);
$birthday = new Zend_Dojo_Form_Element_DateTextBox('birthday');
$birthday->setLabel('Birthday');
$submit = $form->createElement('submit', 'submit');
$form->addElements(array($name, $birthday, $submit));
// We already discussed that the above code does
return $form;
}
}
?>
When the form is submitted we can access the name and birthday values via the usual $this->_getParam() method. In our controller we pass the name and birthday values to the view so that we can print them in our view.
Add the following code to your view file to display the name and birthday values supplied by the user.
<?php
echo "Your name is " . $this->name . "<br>";
echo "Your birthday is " . $this->birthday . "<br>";
echo $this->form ;
?>
In your layout script, you have to add the stylesheet modules and print the dojo object. In this example we use tundra stylesheet.
<?php
<title>
<?php echo $this->escape($this->pageTitle); echo " - Binary Vibes BizSense"; ?></title>
<?php echo $this->dojo();
echo $this->dojo()->addStylesheetModule('dijit.themes.tundra');
?>
</title>
?>Remember to set the body class to tundra.
<body class="tundra">
<div id="content">
<?php echo $this->layout()->content ?>
</div>I have published the complete layout example script below for your reference.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Binary Vibes BizSense</title>
<?php echo $this->dojo();
echo $this->dojo()->addStylesheetModule('dijit.themes.tundra');
?>
</head>
<body class="tundra">
<div id="content">
<?php echo $this->layout()->content ?>
</div>
</body>
</html>That is all there is to it to use Dojo form widgets in your Zend Framework powered application.
Reference:
Zend_Dojo - http://framework.zend.com/manual/en/zend.dojo.html
Dojotoolkit - http://dojotoolkit.org/
Plain HTML and JavaScript DateTextBox usage example - http://techchorus.net/add-cool-date-picker-2-lines-javascript
You want to add an asterisk to required fields, huh?

There are many approaches to accomplish this. One among them is setting the requiredSuffix option to the label decorator of the form element. Assuming $element is your Zend_Form_Element object:
<?php
$element->getDecorator('label')->setOption('requiredSuffix', ' * ');
?>Another option is to add the * while setting the label.
<?php
$element->setLabel('My Label *')
?>The third, which I am currently using in one of my Zend Framework powered applications is adding * using CSS. The default label decorator generates the following mark-up.
<label class="required" for="username">Email address</label>
Here goes the CSS
.required { background-image:url(/path/to/your/images/dir/required-field.png); background-position:top right; background-repeat:no-repeat; padding-right:10px; }
| Attachment | Size |
|---|---|
| required-field.png | 306 bytes |

Zend Framework brings lot of user interface goodies with Zend_Dojo family of classes. In this article let us explore how to build a form element with autocomplete feature.
As a prerequisite you must be familiar with
Would it be nice if I tell you that you don't need any JavaScript knowledge? Zend_Dojo empowers PHP programmers to build dynamic and appealing forms without writing a single line of JavaScript.
This example has been tested with Zend Framework 1.7.0.
In this example, we will build a text element where the visitor can either select the user from the drop down list or type the username. While typing the username, the form element generates a drop down list filtering the data from user input. Take a look at the filteringSelect Dijit example to understand the type of form element we will be building.
FilteringSelect differs from Combobox Dojo widget in that, the value of the form element must be provided in the list. Also, you could display the username on the screen and set the 'user id' as the element value.
We will use the autoCompleteDojo action helper to send JSON data.
Let's start coding.
Step 1: Set up the Dojo environment in our bootstrap file.
<?php
// Create new view object if not already instantiated
//$view = new Zend_View();
Zend_Dojo::enableView($view);
$view->dojo()
->addStyleSheetModule('dijit.themes.tundra')
->setDjConfigOption('usePlainJson', true)
->disable();
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
'ViewRenderer'
);
$viewRenderer->setView($view);
?>In this example, we use the default CDN set in Zend_Dojo. You don't have to add Dojo JavaScript files to your web server. We add the 'tundra' stylesheet.
Step 2: Create the controller. Create the file DemoController.php in your controller directory and add the code below to it.
<?php
class DemoController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function userlistAction()
{
}
public function getForm()
{
}
}
?>We build our form in the function getForm(). In a real world application you might want to create the form in a different class and file. In indexAction we display the form and process the data submitted by the user. In userlistAction we generate the data in JSON format which is required by the filteringSelect element.
Step 3: Create the form and elements. Put the below code in the getForm() function.
<?php
$form = new Zend_Form;
$userId = new Zend_Dojo_Form_Element_FilteringSelect('userId');
$userId->setLabel('Select a user')
->setAutoComplete(true)
->setStoreId('userStore')
->setStoreType('dojo.data.ItemFileReadStore')
->setStoreParams(array('url'=>'/demo/userlist'))
->setAttrib("searchAttr", "username")
->setRequired(true);
$submit = $form->createElement('submit', 'submit');
$form->addElements(array($userId, $submit));
return $form;
?>$userId is the form element containing the Dojo filteringSelect widget. We give the name userStore to our data store. We are specifying that we will serve the data from the URL /demo/userlist. Finally, we are setting the searchAttr to 'username'.
Step 4: Prepare the database.
CREATE TABLE `user` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `username` VARCHAR( 100 ) NOT NULL , ) ENGINE = InnoDB INSERT INTO `zf`.`user` ( `id` , `username` ) VALUES ( NULL , 'jamey' ), ( NULL , 'hryan' ), ( NULL , 'jennyross' ), ( NULL , 'natebrg' ), ( NULL , 'deric' );
Step 5: Fetch the data from the database, convert to JSON format and send. I use the MySQL database 'zf' in this example. Insert below code to userlistAction(). I am connecting to the database from within the action in this example. Practically, you would want to connect to the database in a centrally accessible place like the bootstrap or a front controller plugin.
<?php
$db = new Zend_Db_Adapter_Pdo_Mysql(array(
'host' => '127.0.0.1',
'username' => 'zf',
'password' => 'password',
'dbname' => 'zf'
));
$result = $db->fetchAll("SELECT * FROM user");
$data = new Zend_Dojo_Data('id', $result);
$this->_helper->autoCompleteDojo($data);
?>It takes only three lines to fetch the data and send it in the format Dojo requires. We pass two parameters - id and $result the Zend_Dojo_Data constructor. 'id' is the unique identifier in our database table. The autoCompleteDojo action helper is convenient to use. It disables the layout and viewrenderer. It sets the appropriate headers and sends the data using the Zend_Dojo_Data object.
Point your browser to demo/userlist, you should receive the data in a file. Dojo uses this file via dojo.data.ItemFileReadStore.
Step 6:Set up indexAction(). Add the below code to the indexAction() function.
<?php
$form = $this->getForm();
if ($this->_request->isPost()) {
if ($form->isValid($_POST)) {
/*
* Process data
*/
$userId = $this->_getParam('userId');
//$userId contains the userId input by the user
} else {
$form->populate($_POST);
$this->view->form = $form;
}
} else {
$this->view->form = $form;
}
?>Step 7:Set up the view and layout
In the view script index.phtml write:
<?php
<h1>Demo</h1>
<?php
echo $this->form;
?>In your layout file output the Dojo files and set the body tag to tundra class. When you echo $this->dojo(), links to Dojo JavaScript source files are printed. It also prints the JavaScript code that Zend Framework generates for you.
<?php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php
echo $this->dojo()->addStylesheetModule('dijit.themes.tundra');
?>
</head>
<body class="tundra">
<div id="content">
<?php echo $this->layout()->content ?>
</div>
</body>
</html>
?>Initially it may appear that you have to write a lot of code to get this work. Once you understand the whole process it becomes trivial to build form elements with autocomplete feature.
I have attached the files to this post for your reference.
You might also want to take a look at:
Add A Cool Zend Dojo Date Picker Form Element Without Writing A Single Line Of JavaScript
| Attachment | Size |
|---|---|
| zf-filteringSelect-example.tar_.gz | 11.6 KB |
Create RESTful Applications Using The Zend Framework - Tutorial Series
In our last example, we used Zend_Rest_Route and Zend_Rest_Controller to demonstrate how to map requests to controller actions. We also used the response object to send text content in the HTTP response. In this article let us send appropriate HTTP response codes using the response object.
RFC 2616 describes HTTP response codes to use in various contexts.
In this example, we will use a few response codes
We will cover other HTTP response codes in upcoming articles on the subject.
Let's start coding. Grab the ArticleContoller.php from the article Create RESTful Applications Using The Zend Framework
.
Modify the indexAction() of our ArticleController
<?php
public function indexAction()
{
$this->getResponse()
->setHttpResponseCode(200)
->appendBody("all articles content");
}
?>The Zend_Controller_Response_Abstract class has the method setResponseCode() using which we can set the HTTP response code. If we weren't using Zend Framework, we would simply use the PHP function header().
In this article, we again use cUrl from the command line to view the response. The -v switch to the curl command prints the output in verbose mode.
curl http://zfrest.example.com/article -v
* About to connect() to zfrest.example.com port 80 (#0) * Trying 127.0.0.1... connected * Connected to zfrest.example.com (127.0.0.1) port 80 (#0) > GET /article HTTP/1.1 > User-Agent: curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.12.4.5 zlib/1.2.3 libidn/1.9 libssh2/1.0 > Host: zfrest.example.com > Accept: */* > < HTTP/1.1 200 OK < Date: Sat, 23 Jan 2010 18:11:08 GMT < Server: Apache/2.2.13 (Fedora) < X-Powered-By: PHP/5.2.11 < Content-Length: 20 < Connection: close < Content-Type: text/html; charset=UTF-8 < * Closing connection #0 all articles content
If you observe carefully, the response contains the line
HTTP/1.1 200 OK
Let's perform HTTP POST action on the article resource. We modify the postAction of ArticleController
<?php
public function postAction()
{
$this->getResponse()
->setHttpResponseCode(201)
->appendBody("created the article\n")
->appendBody("http://zfrest.example.com/article/5");
}
?>In the response body we also mention the URI from which the newly created article can be accessed.
The output looks like
curl -d "article=myarticle" http://zfrest.example.com/article/ -v
* About to connect() to zfrest.example.com port 80 (#0) * Trying 127.0.0.1... connected * Connected to zfrest.example.com (127.0.0.1) port 80 (#0) > POST /article/ HTTP/1.1 > User-Agent: curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.12.4.5 zlib/1.2.3 libidn/1.9 libssh2/1.0 > Host: zfrest.example.com > Accept: */* > Content-Length: 17 > Content-Type: application/x-www-form-urlencoded > < HTTP/1.1 201 Created < Date: Sat, 23 Jan 2010 17:52:51 GMT < Server: Apache/2.2.13 (Fedora) < X-Powered-By: PHP/5.2.11 < Content-Length: 55 < Connection: close < Content-Type: text/html; charset=UTF-8 < created the article * Closing connection #0 http://zfrest.example.com/article/5
Let's delete an article. The user agent does not require any content in the body when the article is deleted.
We modify the deleteAction() of ArticleController
<?php
public function deleteAction()
{
$this->getResponse()
->setHttpResponseCode(204);
}
?>The output on the command line looks like:
curl -X DELETE http://zfrest.example.com/article/12 -v
* About to connect() to zfrest.example.com port 80 (#0) * Trying 127.0.0.1... connected * Connected to zfrest.example.com (127.0.0.1) port 80 (#0) > DELETE /article/12 HTTP/1.1 > User-Agent: curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.12.4.5 zlib/1.2.3 libidn/1.9 libssh2/1.0 > Host: zfrest.example.com > Accept: */* > < HTTP/1.1 204 No Content < Date: Sat, 23 Jan 2010 17:58:14 GMT < Server: Apache/2.2.13 (Fedora) < X-Powered-By: PHP/5.2.11 < Content-Length: 0 < Connection: close < Content-Type: text/html; charset=UTF-8 < * Closing connection #0
Let's try to access article 20 which does not exist.
Modify the getAction() of ArticleController. For the sake of example, let's pretend the getAction() is prepared to respond to only non-existent resources.
<?php
public function getAction()
{
$this->getResponse()
->setHttpResponseCode(404)
->appendBody("requested article 20 not found");
}
?>The output looks like:
curl http://zfrest.example.com/article/20 -v
* About to connect() to zfrest.example.com port 80 (#0) * Trying 127.0.0.1... connected * Connected to zfrest.example.com (127.0.0.1) port 80 (#0) > GET /article/20 HTTP/1.1 > User-Agent: curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.12.4.5 zlib/1.2.3 libidn/1.9 libssh2/1.0 > Host: zfrest.example.com > Accept: */* > < HTTP/1.1 404 Not Found < Date: Sat, 23 Jan 2010 18:17:56 GMT < Server: Apache/2.2.13 (Fedora) < X-Powered-By: PHP/5.2.11 < Content-Length: 30 < Connection: close < Content-Type: text/html; charset=UTF-8 < * Closing connection #0 requested article 20 not found
Lastly, let's respond with the HTTP code 503.
Modify the putAction of ArticleController
public function putAction()
{
$this->getResponse()
->setHttpResponseCode(503)
->appendBody("unable to process put requests. Please try later");
}The output looks like:
curl -d "article=updatedarticle" -X PUT http://zfrest.example.com/article/1 -v
* About to connect() to zfrest.example.com port 80 (#0) * Trying 127.0.0.1... connected * Connected to zfrest.example.com (127.0.0.1) port 80 (#0) > PUT /article/1 HTTP/1.1 > User-Agent: curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.12.4.5 zlib/1.2.3 libidn/1.9 libssh2/1.0 > Host: zfrest.example.com > Accept: */* > Content-Length: 22 > Content-Type: application/x-www-form-urlencoded > < HTTP/1.1 503 Service Temporarily Unavailable < Date: Sat, 23 Jan 2010 18:21:48 GMT < Server: Apache/2.2.13 (Fedora) < X-Powered-By: PHP/5.2.11 < Content-Length: 48 < Connection: close < Content-Type: text/html; charset=UTF-8 < * Closing connection #0 unable to process put requests. Please try later
When implementing a REST client you could simply examine the HTTP response code to check whether the request was successful. One common area where you can see response codes being examined is AJAX applications.
For your convenience, I am posting the entire code of the ArticleController.php below.
<?php
class ArticleController extends Zend_Rest_Controller
{
public function init()
{
$this->_helper->viewRenderer->setNoRender(true);
}
public function indexAction()
{
$this->getResponse()
->setHttpResponseCode(200)
->appendBody("all articles content");
}
public function getAction()
{
$this->getResponse()
->setHttpResponseCode(404)
->appendBody("requested article 20 not found");
}
public function postAction()
{
$this->getResponse()
->setHttpResponseCode(201)
->appendBody("created the article\n")
->appendBody("http://zfrest.example.com/article/5");
}
public function putAction()
{
$this->getResponse()
->setHttpResponseCode(503)
->appendBody("unable to process put requests. Please try later");
}
public function deleteAction()
{
$this->getResponse()
->setHttpResponseCode(204);
}
}
?>In the first two posts of this series, we discussed how to route REST requests to controllers and return HTTP response code. In this article I will talk about managing API keys.
Having the clients send API key within the HTTP header is convenient to handle. We can quickly check the HTTP request header and decide whether to allow or deny the request.
As a prerequisite you should be familiar writing front controller plugins. Let's write a front controller plugin that does the following:
We will not perform any changes to our previous article controller.
Let's start writing code.
Step 1: Write the front controller plugin.
Create the directory library/My/Controller/Plugin.
Inform the autoloader about the namespace 'My'. Also, register the plugin "My_Controller_Plugin_RestAuth". Let's add these lines to our configuration file application/configs/application.ini generated by Zend_Tool(or the quick start guide).
autoloadernamespaces.1 = "My_" resources.frontController.plugins = "My_Controller_Plugin_RestAuth"
Let's write the front controller plugin. Create and edit the file library/My/Controller/Plugin/RestAuth.php
<?php
class My_Controller_Plugin_RestAuth extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$apiKey = $request->getHeader('apikey');
if ($apiKey != 'secret') {
$this->getResponse()
->setHttpResponseCode(403)
->appendBody("Invalid API Key\n")
;
$request->setModuleName('default')
->setControllerName('error')
->setActionName('access')
->setDispatched(true);
}
}
}
?>In our front controller plugin, we hook into the preDispatch() method. Before a controller action is executed, our Predispatch() method is called.
In our preDispatch() method, we check whether the HTTP request header contains the key 'apikey' with value 'secret'. If the request does not have the correct API key we set the 403 HTTP response code and set the controller and action to 'error' and 'access' respectively. We also set the dispatched status to true.
Step 2: Add the 'access' action to the error controller in application/controllers/ErrorController.php.
<?php
public function accessAction()
{
$this->_helper->ViewRenderer->setNoRender(true);
}
?>In the sample code, we simply disable the view. In your application, you could perform logging in the access action of the error controller.
Step 3: Let's test our application using cUrl.
Make a request without sending the 'apikey' HTTP header.
curl http://zfrest.example.com/article -v
The sample output of the above command looks like:
* About to connect() to zfrest.example.com port 80 (#0) * Trying 127.0.0.1... connected * Connected to zfrest.example.com (127.0.0.1) port 80 (#0) > GET /article HTTP/1.1 > User-Agent: curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.12.4.5 zlib/1.2.3 libidn/1.9 libssh2/1.2 > Host: zfrest.example.com > Accept: */* > < HTTP/1.1 403 Forbidden < Date: Mon, 01 Mar 2010 08:46:03 GMT < Server: Apache/2.2.14 (Fedora) < X-Powered-By: PHP/5.3.1 < Content-Length: 16 < Connection: close < Content-Type: text/html; charset=UTF-8 < Invalid API Key * Closing connection #0
We recieved the HTTP response code 403 with the body content 'Invalid API Key'.
Let's make another test. This time, let's add the correct API key in the request HTTP header.
curl -H "apikey: secret" http://zfrest.example.com/article -v
Using the -H switch, we can send headers.
The output :
* About to connect() to zfrest.example.com port 80 (#0) * Trying 127.0.0.1... connected * Connected to zfrest.example.com (127.0.0.1) port 80 (#0) > GET /article HTTP/1.1 > User-Agent: curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.12.4.5 zlib/1.2.3 libidn/1.9 libssh2/1.2 > Host: zfrest.example.com > Accept: */* > apikey: secret > < HTTP/1.1 200 OK < Date: Mon, 01 Mar 2010 08:57:15 GMT < Server: Apache/2.2.14 (Fedora) < X-Powered-By: PHP/5.3.1 < Content-Length: 20 < Connection: close < Content-Type: text/html; charset=UTF-8 < * Closing connection #0 all articles content
This time we received the HTTP response code 200 with body content 'all articles content'.
Reference:
Writing front controller plugins
The Zend Framework 1.9 release added a new feature - Zend_Rest_Controller. Zend_Rest_Controller and Zend_Rest_Route classes go hand in hand. In the previous versions of the Zend Framework, we have had the Zend_Rest_Server component. We still have. Since Zend_Rest_Server provides an RPC like component violating the REST architectural constraint, it is likely to be deprecated in the future versions of the Zend Framework.
In this article let us explore how to make use of Zend_Rest_Route and Zend_Rest_Controller to build a RESTful server application. Zend_Rest_Route routes the request to the appropriate module, controller and action depending on the HTTP request method and URI.
Let's start coding. We build the RESTful application based on the QuickStart project.
You can choose to enable Zend_Rest_Route for the entire application or for specific set of modules. In this example we enable the rest route for the entire application.
Bootstrap the front controller resource and add the rest route.
<?php
protected function _initRestRoute()
{
$this->bootstrap('frontController');
$frontController = Zend_Controller_Front::getInstance();
$restRoute = new Zend_Rest_Route($frontController);
$frontController->getRouter()->addRoute('default', $restRoute);
}
?>Create the file application/controllers/ArticleController.php. We extend Zend_Rest_Controller instead of Zend_Controller_Action. In our controller we are going to have five actions.
These actions are defined as abstract methods in the Zend_Rest_Controller class.
The skeletal controller looks like:
<?php
class ArticleController extends Zend_Rest_Controller
{
public function init()
{
$this->_helper->viewRenderer->setNoRender(true);
}
public function indexAction()
{
}
public function getAction()
{
}
public function postAction()
{
}
public function putAction()
{
}
public function deleteAction()
{
}
}
?>To test the routing of the requests, let's append sample messages to the response object in each action.
<?php
public function indexAction()
{
$this->getResponse()
->appendBody("From indexAction() returning all articles");
}
public function getAction()
{
$this->getResponse()
->appendBody("From getAction() returning the requested article");
}
public function postAction()
{
$this->getResponse()
->appendBody("From postAction() creating the requested article");
}
public function putAction()
{
$this->getResponse()
->appendBody("From putAction() updating the requested article");
}
public function deleteAction()
{
$this->getResponse()
->appendBody("From deleteAction() deleting the requested article");
}
?>On my computer I have installed this application for the domain zfrest.example.com. We use the curl command to test our RESTful server.
Testing the indexAction() : The URI http://zfrest.example.com/article represents the article resource. All articles are returned for this request.
$ curl http://zfrest.example.com/article
I get the following output:
From indexAction() returning all articles
Testing the getAction() : The URI http://zfrest.example.com/article/1 represents the resource - article 1.
$ curl http://zfrest.example.com/article/1
I get the following output:
From getAction() returning the requested article
Testing the postAction() : we make an HTTP POST request to http://zfrest.example.com.
$ curl -d "article=myarticle" http://zfrest.example.com/article/
I get the following output:
From postAction() creating the requested article
Testing the putAction() : we request the article 1 to be updated by making HTTP PUT request to http://zfrest.example.com/article/1
$ curl -d "article=updatedarticle" -X PUT http://zfrest.example.com/article/1
I get the following output:
From putAction() updating the requested article
Testing the deleteAction() : we send an HTTP DELETE request to http://zfrest.example.com/article/1
curl -X DELETE http://zfrest.example.com/article/1
I get the following output:
From deleteAction() deleting the requested article
Zend Framework allows you to build RESTful server applications using the Zend_Rest_Controller component. The curl command is a very useful tool to test RESTful servers. If you don't have the curl command on your computer, you can write a PHP script and make use of the curl extension provided by PHP. In the upcoming posts of this series, I will discuss managing API keys from your RESTful application, returning appropriate HTTP response codes, reading the body from PUT and DELETE requests and more.
Are you going to a build RESTful server using the Zend_Rest_Controller component? Tell me about your experiences.
Create RESTful Applications Using The Zend Framework - Part II : Using HTTP Response Code
Reference:
Wikipedia article on Representational State Transfer
Zend_Rest_Route - Zend Framework manual page
If you are using MVC components of Zend Framework, you will come across situations where you will have to disable view and layout. To do so you use the viewRenderer and layout action helpers and call the setNoRenderer() and disableLayout() methods respectively.
In your controller action
<?php
$this->_helper->viewRenderer->setNoRender(true);
?>In your controller action
<?php
$this->_helper->layout->disableLayout()
?>Did the code snippet solve your problem?
The request object contains the name of the module, controller, action and the request parameters. Sometimes, you might want to access the request object outside the controller or controller plugin.
For example a user on #zftalk just asked
"how can I access request object within form's method?"
The front controller instance is a singleton. This means we can get the instance of the front controller from any part of our application using the static method getInstance().
To grab the front controller instance use:
<?php
$frontController = Zend_Controller_Front::getInstance();
?>We can access the request object from the front controller intance:
$request = $frontController->getRequest();
Using the fluent interface you can access the front controller in a single line:
$request = Zend_Controller_Front::getInstance()->getRequest();
If you want to access the front controller in your action just use:
$request = $this->getRequest();
From your view helepr you might want to access
You will be able to do all of the above if the view object is available in your view helper. To make sure view object is available to your helper do any of the following
<?php
class My_View_Helper extends Zend_View_Helper_Abstract{}
?><?php
public $view;
function setView(Zend_View_Interface $view) {
$this->view = $view;
}
?>Once the view object is accessible in your view helper, you can call another view helper. For example,
<?php
$this->view->OtherHelper();
?>Many people think 'Zend' is the latest trend in PHP. They also think the popular PHP library out there is called Zend.
These notions are absolutely wrong. Before you start working with Zend Framework, get to know the facts.
Zend is a company that has several products - Zend engine, Zend Studio, et all. Zend develops a PHP library with community contributions. This library or framework is known as the Zend Framework.
If you find yourself saying something like , "I tried Zend and I didn't like it, so I use Cake", it is high time you read more about these:
http://www.zend.com/
http://framework.zend.com/
http://www.zend.com/en/community/php
http://php.net
In summary, Zend is the company which develops a PHP library called Zend Framework.
ZF, the abbreviation, my friend, is the better short cut.
A few months back, our friend Ben Scholzen wrote about setting up the environment variable in your Zend Framework powered application.
With the advent of Zend Framework 1.8 and the Zend_Application component the Zend Framework Quick Start guide recommends this setting.
Handling exceptions and errors, using the same code for production, testing and staging are now easier when you define the application environment.
How do you programatically alter the value of this variable? You could write simple scripts to alter the value of the environment variable.
Solution 1: Use sed
sed -i 's/SetEnv APPLICATION_ENV development/SetEnv APPLICATION_ENV production/g' path/to/.htaccesss <path/to/.htAccess
Solution 2 Use PHP
<?php
$contents = file_get_contents('.htaccess');
$newString = str_replace("SetEnv APPLICATION_ENV development", "SetEnv APPLICATION_ENV production", $contents);
file_put_contents('.htaccess', $newString);
?>Using any of the above two snippets of code you can programatically alter the value of the environment variable from 'development' to 'production' and vice versa.
Zend Framework is an open source, object-oriented web application framework implemented in PHP 5 and licensed under the New BSD License. Zend Framework provides many components like Zend_Form, Zend_Controller, Zend_Validate, Zend_Filter to build web secure and robust applications fairly faster.
To know more about Zend Framework visit the following websites:
Zend_Form official reference guide is available at http://framework.zend.com/manual/en/zend.form.html
Zend_Form simplifies form creation and handling in your web application. Taking advantage of Zend_Filter and Zend_Validate you can filter and validate your form fields. At the time of writing this article 19 validation classes are shipped with Zend Framework. I came across a situation where I had to write a custom class to validate URIs. To write the custom URI validator I made use of Zend_Uri which aids in manipulating and validating Uniform Resource Identifiers (URIs). In particular I used Zend_Uri::check() function to validate the URI in question.
In order to use BV_Validate_Uri you must have set up your application to use Zend Framework. You must also know how to use Zend_Form to validate the form fields.
Create the directory BV under your Zend Framework library directory. Also create the directory Validate under BV. Create a file by name Uri.php and copy the PHP code to it.
mkdir library/BV mkdir library/BV/Validate vi library/BV/Validate/Uri.php Copy the below PHP code and save the file
<?php
require_once 'Zend/Validate/Abstract.php';
require_once 'Zend/Uri.php';
class BV_Validate_Uri extends Zend_Validate_Abstract
{
const MSG_URI = 'msgUri';
protected $_messageTemplates = array(
self::MSG_URI => "Invalid URI",
);
public function isValid($value)
{
$this->_setValue($value);
//Validate the URI
$valid = Zend_Uri::check($value);
//Return validation result TRUE|FALSE
if ($valid) {
return true;
} else {
$this->_error(self::MSG_URI);
return false;
}
}
}
?>
Now we have created a reusable URI validator. You can use this URI validator in all your forms. Below is an example of the BV_Validate_Uri usage with Zend_Form.
<?php
$website = $form->createElement('text', 'website');
$website->setLabel('Website URL');
$website->addValidator(new BV_Validate_Uri());
?>
That is all you need to do to add the BV_Validate_Uri to your form field. When the form is submitted the element is validated by BV_Validate_Uri. In summary, you just have to add one line to add the custom URI validator.
<?php
$website->addValidator(new BV_Validate_Uri());
?>
I hope this article has helped you to validate URI in your form fields.
Is the value of your Zend_Dojo_Form_Element_DateTextBox form element set to 11/30/1899?
The issue is actually Dojo related. You are most likely setting the value of the form element to '0000-00-00' using the populate() method of the Zend_Form or the setValue() method of the Zend_Form_Element. It so happens in a PHP/MySQL application, you provide a form field to enter the date to the user. The user supplies null value. You insert or update the record in your database. In the database the value is represented as '0000-00-00'. The next time you provide the form to the user, perhaps a data edit form, you populate the form with the values in the database and the user notices that the value is set to 11/30/1899.
Dojo sets the dateTextBox element's value to '11/30/1899', if you try to set it to '0000-00-00'.
To avoid this issue, before setting the form element's value, check if the date is valid. You can check if a date is valid in one line in your Zend Framework application.
<?php Zend_Date::isDate($myDate); ?>
Here's an snippet of code to illustrate the solution.
$birthdayInModel = $myModel['birthday'];
if (! (Zend_Date::isDate($birthdayInModel)) ) {
$myZendDojoFormElementDateTextBox->setValue('');
}