Sunday, August 05, 2012

Understanding Zend Framework’s Plugin: Controller Action Helper Plugin, and View Helper...(Part Two)

Last week I started off with the first post in a series of post on plugins as you have in Zend Framework. This is the second part of the series, where I would look at Zend framework’s Controller Action Helper and View Helper, since the previous post covered Simple Class plugin and Front Controller plugin - you can read it here.
As I said in my previous post, the idea behind these series of posts is to shed some light on plugins and the different incarnation that exists within Zend framework;


Controller Action Helper

First let me start by explicitly saying that Controller Action Helper and Front Controller Plugin are different, although they may sound alike. Read about Front Controller Plugin here.

Controller Action Helpers are the kind of Plugins that are tied to your Controller Actions, and just as Front Controller plugin, they can run specific tasks at some predefine stages of the MVC cycle; though this isn't mandatory. The key difference between Front controller plugins and Controller Action Helper is that your controllers can interact with action helpers to change their behavior, or use some on-demand functionality while this is not the case with Front Controller plugins.




How to write and use a Controller Action Helper
Like every other plugin you have in Zend framework, your Controller Action helper is just another PHP Class with specialized properties based on the class it extends.

The first step is to create your class file and put it in the most appropriate place. For Controller Action Helper, the preferred way is to have a Helper directory inside your Controller Folder that would house all your Action Helpers.
This is not necessarily the case every time. Your action helpers can exist outside of your controller folder and still work. For instance, if you have a helper that applies to all controllers, then you can as well have the Helpers in the Library directory.

So let’s say we go with the preferred way, (having a helper directory in the Controller directory for our helpers) and we have a Controller Action Helper class file called help.php we would have the following director structure
/path/to/app
       Application/
               Configs/
               controllers/
            helpers/
        help.php

Inside your help.php you can have the following code
class Zend_Controller_Action_Helper_Help extends Zend_Controller_Action_Helper_Abstract
{
 Public function init()
 
 {
  echo “SOS!";
 }

              Public function postDispatch()
 {
        }

Public function preDispatch()
 {
        }

Public function scream()
       {
              Echo “Can someone please help!!!”;
       }

}


Note that the class extends Zend_Controller_Action_Helper_Abstract and the class Help is prefixed by Zend_Controller_Action_Helper_

Also notice, the Class has some familiar methods: notable PostDispatch() and preDispatch() methods. This is because Controller Action Helpers too have unique methods which can be implemented that allow us to invoke custom functionalities at different time in the code execution. Some of the method includes:

  • getActionController()
    used to get the current action controller.
  • init()
    triggered by the helper broker at instantiation, can be used to trigger initialization in the helper; this can be useful for resetting state when multiple controllers use the same helper in chained actions.
  • preDispatch()
    triggered prior to a dispatched action.
  • postDispatch()
    triggered when a dispatched action is done -- even if a preDispatch() plugin has skipped the action. Mainly useful for cleanup.
  • getRequest()
    retrieves the current request object.
  • getResponse()
    retrieves the current response object.
  • getName()
    retrieves the helper name. It retrieves the portion of the class name following the last underscore character, or the full class name otherwise.

So once you have your Action Helper code written, the next thing you need to do is to configure your Zend Application to be aware of the Controller Action Helper. There are two ways to do this.
1) Via Application.ini
2) Via Bootstrap.

Via Application.ini
To use the application.ini approach, just include the following in your application.ini

resources.frontController.actionHelperPaths.help = APPLICATION_PATH "/controllers/helpers"

The bold text is the name of the Helper. In this example, it’s help. And the value of this key point to the location of the helper files for the application.

That is APPLICATION_PATH "/controllers/helpers"

Once you have this set up this way, your Action Helper is ready to be used.

Via Bootstrap.php
To use the bootstrap.php approach, you can have the following code in your Bootstrap.php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public function _initLoader()
{
 Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .'/controllers/helpers'); 
}
}

If you want to change the prefix to the class name from Zend_Controller_Action_Helper_ to something of your choice,
you should add this as the second variable of the ::addPath method
i.e.

Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .'/controllers/helpers', 'My_Own_Prefix_');

When you have this, you must edit your Controller Action file above to class

Class My_Own_Prefix_Help extends Zend_Controller_Action_Helper_Abstract

With the following code in your Bootstrap, your Zend application would be aware of your Action Helper. This is the second way of doing it.

Using the Controller Action Helper

Now that you have your Action Helper code written and your application is properly configured, the next thing is being able to use it.
In your action, you can access your Helper class via the _helper broker. So to use the scream() method that we have in the code above in your action, you just have


class IndexController extends Zend_Controller_Action
{
    public function init()
    {
        /* Initialize action controller here */
    }
    public function indexAction()
    {
 $this->_helper->help->scream();
    }
}


And that is it!!
Remember you can always make use of the predefined hooks of Action Helpers and have code injected at stages of the MVC cycle.


View Helpers


View Helpers are to Views what Controller Action Helpers are to Controllers. View helpers are just simply what make it possible to develop codes that are specific to Views.

A View Helper is a method added to the view objects which you can easily use in the view script.

For example, in your view script you can have something similar to this

echo $this->showCountries();

Where showCountries() is a method that generates the list of countries and display it in an HTML select format.

The showCountries() method is one example of a View Helper. View Helpers are the means by which Zend Framework provides you with customized code or functionality available in your view script.

Zend framework comes with various View Helpers you can easily use in your project. You can find more information about these View Helpers on the documentation page:

What about writing your own View Helpers? Find out how below:

How to write and use a View Helper
Just like every other Zend framework plugin, the View Helper is a class. By default Zend Framework looks for View helper class file in the following location

1. The folder called helpers within the views
2. The Folder called Helpers with the Layout folder

You can also have your View Helper class in a location of your choosing; say in the Library/Myviewhelper/ location.

Let us see how View Helpers look like in Default location

View Helpers in Default Location
Let’s say we want to implement the showCountries() method, using the default locations, we create a file showcountries.php inside the View folder found in the Module or in the Layout folder. The code might look like this

class Zend_View_Helper_showcountries extends Zend_View_Helper_Abstract
{
 public function showCountries()
 {
  //code to connect to a database
       //Get all the countries and format it as select HTML
            //Return the HTML string
 }
} 

Notice that the Class prefix is Zend_View_Helper_ this is the case when the file is placed inside the default locations.

And that is it. You can now proceed to the View files and call the showcountries() function

echo $this->showCountries(); 

It is that simple!

Two things to take note of: First, is that you only have one method and the method name should be the name of the Class file and this would be name of the method that would be called in the view script. For the example above, the method is showCountries()

The second thing to note is that the convention is to have your View Helpers returns the string and then the view script echoes it.

View Helpers in Location of Choice
For varied reasons you might want your View helpers located in a different location other than the default, perhaps you want a View Helper that is accessible site wide and not specific to a module.

To do this, follow the steps:
1. Create a new folder say 'Helpers' inside your 'Library' folder
2. Put your View Helper File inside a file you would name 'showcountries.php'
3. Inside the showcountries.php you have the following code:

class Helpers_ showcountries extends Zend_View_Helper_Abstract
      {   
           public function showCountries()
 {
  //code to connect to a database
       //Get all the countries and format it as select HTML
            //Return the HTML string
 }
   
}

And in your Application.ini add the view helper path as follows so your application is aware of the View Helper:

resources.view.helperPath.Helpers = "Helpers/"

And once you have it this way, you can then go ahead and use your custom View Helper in your view scripts.

And that is it for this post. Do not forget to check the previous post for how Front Controller plugin and Simple Class plugin works. Next post would be on Zend Framework’s Resource Plugin.

4 comments:

Anonymous said...

Thanks dear

you have a lots of thanks

i am new for Zend and this tutorial give me a clear cut knowledge about Zend plugin.

santu said...

Thanks for the tutorials

Andrew Simon said...

Thanks for sharing the information. I was looking for the same option to simply make my task easy. A great piece of tool. I really appreciate your efforts for the post.

Andrew Simon said...

Thanks for sharing the information. I was looking for the same option to simply make my task easy. A great piece of tool. I really appreciate your efforts for the post.