Sunday, July 22, 2012

Understanding Zend Framework’s Plugin: Front Controller Plugin, Controller Action Helper, View Helper, Resource Plugin...(Part One)

This post is the first of three posts on Zend Framework's plugin. It would give a quick overview of the concepts of Plugins in Zend Framework. The aim is to provide an easy and short explanation of various plugin related concepts in zend framework; making it easy for a new comer to get up and running in no tim.

Usually, after getting the basics of Zend framework; that is: setting up your projects, using the Zend_Tool,  using controllers and views etc, more often than not, the next points of confusion for the new user usually stems from having to grapple with the various minor concepts within Zend framework.

An example of these concepts is the idea of Plugins. Plugins by itself is a simple concept right? But within Zend Framework, there are so many variant of plugins that it could quickly get perplexing to a new user.

What is a Front Controller Plugin? What is a Resource Plugin? What about our View Helpers? How are these different from Controller Action Helper? Wait. There is a Controller Action Helper? How is it different from our Front Controller Plugin? As you could get confusing pretty fast.

Like I said in my previous post on how to set up a modular application structure, zend framework itself is not inherently difficult, just that it could take a while to wrap a head around how everything fits together, plus the paucity of useful and up to date resources out there does nothing to help matters.

So with this post I seek to shed some light on Plugins and the different common incarnations that we have within Zend framework. It would be brief. I would give a simple introduction to the different types of plugin, how they are created and how they are set up. I would not go into details about the workings of the plugins; that would be for other times.

In this post, I would cover the Simple Class Plugin and Front Controller plugin while the remaining types would be covered in the second part of this post.

This been said, let us start.

So what is a Plugin. In the context of Zend framework I would describe it as a written Class with methods that can be invoked programmatically by the programmer in other parts of the application or automatically during the execution of Request/Response operations of Zend Framework.

Going by the above definition, I can easily say we have the following kinds of plugins

  1. Simple Class Plugin
  2. Front Controller Plugin
  3. Controller Action Helper
  4. View Helper
  5. Resource Plugin

Your simple class plugin can be described as classes that you write to take care of a specific task which does not necessarily have to depend on any of the callbacks or hooks you have within Zend Framework request/response operation.

It’s basically the same way you have a class that performs a specific task, you include it using PHP's include function and you can instantiate its object and use its functionality.

How to write and use a Normal Plugin
  1. Start by indicating to Zend Framework where your Class would be located so it can auto-load it. You do this by defining a default Namespace. Your namespace is technically the directory where your class would reside i.e. where Zend framework would autoload it from. To do this, add the following entry into you application.ini file:

    autoloaderNamespaces[] = "Ext_"

    Ext is thus the directory and your namespace. And this directory should be created inside the Library Directory.

  2. Next is to create your class file and have it saved inside the Ext directory. For example if we are writing a plugin that does a simple task of printing the current date, we can create a file and save it as date.php.
  3. Then write the code of your class:
          Class Ext_date
      Public function echoDate()
       echo date("Y-m-d H:i:s")

Notice that the class name is a combination of the Namespace you defined and the name of the file. This should be the case if you want Zend Framework to be able to find your class; having it this way, you have your Plugin created and ready to be used.

You make use of it like you make use of any other PHP class. 

$dateutiliy = new Ext_date()

Note that the Ext_date is made available for you and can be called from anywhere within your Zend project: be it inside a controller, view, model or your bootstrap.

Front controller plugin are the type of plugin you have which are designed to perform certain tasks at specific stages in the MVC cycle. You can use it to perform stuffs like checking whether a user is authenticated or logging requests to a database for analytics. 

Zend Framework implements the Front Controller design pattern. The Front controller plugin hence allows you insert specific functionality into the Front controller process. This is different from Controller Action Plugin as a Controller Action Plugin fits into the Actions of Controllers.

How to write and use a Front Controller Plugin

The process would involve two steps. One, creating the Front Controller Plugin File and two, configure Zend Framework to be aware of the Front Controller Plugin File.

Creating your Front Controller Plugin File

  1. Have a namespace defined. So just like in the previous example, you can set up a namespace by adding this to your application.ini

    autoloaderNamespaces[] = "Ext_"
    And have a directory Ext created inside your Library directory.
  2. Now create your Class file. Let say we have a front controller plugin file called fcplugin.php create this file and save it inside the Ext directory.
  3. Inside the fcplugin.php file you may have the following code

Class Ext_fcplugin extends Zend_Controller_Plugin_Abstract

Public function __construct()

Private function myInnervoice()
/*shows that you can have your own custom methods*/

return “I want chocolate”;


Public function 
routeStartup(Zend_Controller_Request_Abstract $request)
/*implementing one of the methods available in Zend_Controller_Plugin_Abstract*/

$this->getResponse()->appendBody("routeStartup() called And my inner voice says ".$this->myInnervoice());


Public function 
dispatchLoopShutdown(Zend_Controller_Request_Abstract $request)
/*implementing one of the methods available in Zend_Controller_Plugin_Abstract*/

$this->getResponse()->appendBody("dispatchLoopShutdown() called
And my inner voice says ".$this->myInnervoice());



Uniqueness of Front Controller Plugin.

To have a Front Controller Plugin your class needs to extend Zend_Controller_Plugin_Abstract, and as such you have specialized methods that you have defined that you can implement in your class that makes it possible for you to have your code run at different part of the MVC operation.These are hooks. It is in this, you have the plugin classified as a Front Controller Plugin.

The Methods you have are:

called before Zend_Controller_Front calls on the router to evaluate the request against the registered routes.
called after the router finishes routing the request.
called before Zend_Controller_Front enters its dispatch loop.
called before an action is dispatched by the dispatcher. This callback allows for proxy or filter behavior. 
called after an action is dispatched by the dispatcher. This callback allows for proxy or filter behavior. By altering the request and resetting its dispatched flag 
called after Zend_Controller_Front exits its dispatch loop.

And as such you can have your class implement these methods and have your code executes at the different stage of the Front controller dispatch operation.

Another thing to note is that the methods implemented have to be supplied an object of type Zend_Controller_Request_Abstract as variable. This is done via Type hinting. Read on Type Hinting here

After you have your code all written up and your plugin is complete, the next thing you need to do is to configure Zend Framework to be aware that your Plugin is in existence.

Configuring Zend Framework to be aware of your Front Controller Plugin

This can be done via two ways.

A) Via Application.ini (my preferred way)
B) Via Bootstrap.php

Via Application.ini
To configure via your Application.ini just include the following settings:

resources.frontController.plugins[] = Ext_fcplugin

It is as simple as that.

Via Bootstrap.php
To use Bootstrap.php to make your application aware of your Front Controller Plugin, then you have your Bootstrap.php looking like below:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
   public function _initLoader()
     $front = Zend_Controller_Front::getInstance();
     $front->registerPlugin(new Ext_fcplugin());

As you can see, what we did was to grab Zend_Controller_Front class and use one of its methods “registerPlugin” to make the application aware of the front Controller Plugin.

Zend Framework does provide some Controller Plugin out of the box that you can make use of.

Read about these from the Documentation page:

That is for this post - Simple Class Plugin and Zend Framework's Front Controller Plugin. Once you have these basic understanding, it is much easier to delve deeper into the workings of the framework.

The next post coming up would cover the Controller Action Helper and View Helper Plugin.


Unknown said...

Very helpful article. Thanks.

lukscito said...

Article very clear!
Thank you!