Front controller

The concept of front controller no longer exists in ZF2. In this new version of the framework, any class that implements DispatchableInterface can be a MVC controller.

interface DispatchableInterface
{
public function dispatch(Request $request, Response $response = null);
}

As you can see, this interface only defines one method: dispatch. You can create a controller following this approach, but you will need to define this method and the logic in every controller or in a parent controller. In such cases, it's much better to use the already coded AbstractActionController that provided this method and the logic required to dispatch a request.

The MVC layer of ZF2 provides a few more interfaces that you can implement to provide the controllers with even more functionality. Let's take a look at the common interfaces that can be used with controllers.

InjectApplicationEvent

This interface is used to tell the Application instance to inject its MvcEvent into this controller. The controller can access the request, response, and route matched using the MvcEvent object and can modify the contents if needed. Let's see an example on how this interface can be used inside a controller to validate that the parameter id is present in the request:

$matches = $this->getEvent()->getRouteMatch();
$id      = $matches->getParam('id', false);
if (!$id) {
    $response = $this->getResponse();
    $response->setStatusCode(500);
    $this->getEvent()->setResult('Invalid identifier; cannot complete request'),
    return;
}

The InjectApplicationEvent class defines two methods: setEvent() and getEvent(). If you take a look at the first line of the previous code example, you can see that we are calling getEvent() to retrieve the MvcEvent object; from there we will call getRouteMatch() to get the RouteMatch object. From there it's just a matter of getting a parameter providing false as the default value. In case the parameter is not in the request, false will be returned and the condition below will succeed taking care of returning the proper error.

ServiceLocatorAware

In ZF2, you usually develop your controllers in a way that the dependencies are injected on the constructor or using setters. Sometimes you can have objects that will not be needed on every request handled by the controller and it makes no sense to have it injected every time, for example during navigation, forms, and pagination. In this case, you will need to use the ServiceLocatorAware interface to tell ServiceManager to inject itself to the controller so that you can use it to retrieve the dependencies you need.

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $config = $this->getServiceLocator()->get('ApplicationConfig'),

        //More code here

    }
}

This is a usage example of this interface. As you can see on the class definition, we are extending the AbstractActionController class. We said before that this controller already provides some boilerplate code; in this case, this class not only implements this interface but also implements InjectApplicationEvent and EventManagerAware. So, if you stick with it while developing your controllers, you will benefit from this automatically.

As in the case of the previous interface, this one also defines two methods: setServiceLocator() and getServiceLocator().

EventManagerAware

As with the other two interfaces, this one is also to tell ServiceManager that we want something injected by default. In this case, we want the EventManager instance to be injected by default. This interface defines two methods: setEventManager() and getEventManager().

Let's see how to use it on a controller:

$eventManager = $this->getEventManager();
$eventManager->trigger(INDEX_LOADED);

As you can see, once the interface is implemented, it is easy to retrieve the EventManager instance and use it; in this case we are firing a custom event called INDEX_LOADED.

Controller plugins

The MVC layer of Zend Framework 2 not only provides interfaces to help you with controllers but also provides plugins to use inside controllers. There are a few types, but the most common ones are URL, Redirect, FlashMessenger, and PostRedirectGet. In order to ease the usage of these plugins, ZF2 provides PluginManager. As usual, to utilize it you should define three methods: setPluginManager(), getPluginManager(), and plugin(), unless you are extending the AbstractActionController class that provides this by default.

$pm = $this->getPluginManager();
$flashMessenger = $pm->get('FlashMessenger'),
$flashMessenger->addMessage('Using the flash messenger plugin'),

As you can see in the example, it is pretty straightforward; you only need to get the PluginManager configuration, and then get any plugin you need, referencing them by name as in the previous code example, the FlashMessenger view helper.

Controller types

The last thing provided by the new implementation of the MVC pattern in ZF2 is a collection of two base controllers that we can extend to create our controllers. These two base controllers are designed to provide some functionality by default and both of them extend a common controller called AbstractController.

AbstractActionController

As you probably may have noticed, ZF2 provides a controller called AbstractActionController that implements all the interfaces we discussed in this chapter. This should be your starting point for a controller. For sure you can create it from scratch if you need it, but it will be simpler and will require less duplication of code if we choose this provided controller at the start.

To be able to work, this controller has two conventions. The controller expects an action parameter defined in the RouteMatch object, which means you have to define the parameter when you define the route itself. Also, the second constraint is that the action parameter will be converted to camelCase format, and then we will append the word action to create the method name, which means that a method with the final name should be present on the controller. The controller will check if the method exists, otherwise the method notFoundAction() will be executed.

From a global point of view, if we are using this type of controller as starting point we will need to define controller and action parameters in all the routes in order to tell the router and dispatcher who has to fulfill the request.

namespace FooController;

use ZendMvcControllerAbstractActionController;

class BarController extends AbstractActionController
{
    public function bazAction()
    {
        return array('title' => __METHOD__);
    }

    public function batAction()
    {
        return array('title' => __METHOD__);
    }
}

As you can see, a controller extending AbstractActionController is pretty short, easy, and simple, compared to controllers made from scratch.

AbstractRestfulController

This is also a specialized version of AbstractController. In this case, this controller will help us when we create RESTful web services.

This controller will map all the actions used on a RESTful approach to predefined methods that we have to implement by convention. Let's see how the HTTP methods and controller methods are connected.

HTTP method

Controller method

Parameters

Description

GET

get()

getList()

id. Optional

If the id parameter is passed as an argument, get() will be called; otherwise getList() is executed.

POST

create()

$data

This method expects the data as an argument, usually the $_POST superglobal array.

PUT

update()

id

An id parameter must be present on the request to be able to update the entity based on the provided data.

DELETE

delete()

id

This method also needs an id to identify which entity to delete.

Also, this controller has some constrains about the response it should generate for each action and the response codes each one should have.

HTTP method

Response code

Headers

Body content

GET

200

Nothing extra

get() will return one entity and getList() a list of entities

POST

201

The Location header should provide the URL of the entity

The body should contain the representation of the entity

PUT

200 or 202

Nothing extra

A representation of the entity should be returned

DELETE

200 or 204

Nothing extra

EMPT.

The controllers that extend this one can also be used as a normal controller; this means that you can still define methods ending in action and call them as usual. This can be useful to organize the code that shows a form for example and the code that actually processes the data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.88.249