When using the AbstractActionController or AbstractRestfulController, or if you implement the setPluginManager method in your custom controllers, you have access to a number of pre-built plugins. Additionally, you can register your own custom plugins with the manager.
The built-in plugins are:
If your controller implements the setPluginManager, getPluginManager and plugin methods, you can access these using their shortname via the plugin() method:
1 | $plugin = $this->plugin('url');
|
For an extra layer of convenience, both AbstractActionController and AbstractRestfulController have __call() implementations that allow you to retrieve plugins via method calls:
1 | $plugin = $this->url();
|
The AcceptableViewModelSelector is a helper that can be used to select an appropiate view model based on user defined criteria will be tested against the Accept header in the request.
As an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class SomeController extends AbstractActionController
{
protected $acceptCriteria = array(
'Zend\View\Model\JsonModel' => array(
'application/json',
),
'Zend\View\Model\FeedModel' => array(
'application/rss+xml',
),
);
public function apiAction()
{
$viewModel = $this->acceptableViewModelSelector($this->acceptCriteria);
// Potentially vary execution based on model returned
if ($viewModel instanceof JsonModel) {
// ...
}
}
}
|
The above would return a standard ZendViewModelViewModel instance if the criteria is not met, and the specified view model types if the specific criteria is met. Rules are matched in order, with the first match “winning.”
The FlashMessenger is a plugin designed to create and retrieve self-expiring, session-based messages. It exposes a number of methods:
Additionally, the FlashMessenger implements both IteratorAggregate and Countable, allowing you to iterate over and count the flash messages in the current namespace within the session container.
Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public function processAction()
{
// ... do some work ...
$this->flashMessenger()->addMessage('You are now logged in.');
return $this->redirect()->toRoute('user-success');
}
public function successAction()
{
$return = array('success' => true);
$flashMessenger = $this->flashMessenger();
if ($flashMessenger->hasMessages()) {
$return['messages'] = $flashMessenger->getMessages();
}
return $return;
}
|
Occasionally, you may want to dispatch additional controllers from within the matched controller – for instance, you might use this approach to build up “widgetized” content. The Forward plugin helps enable this.
For the Forward plugin to work, the controller calling it must be ServiceLocatorAware; otherwise, the plugin will be unable to retrieve a configured and injected instance of the requested controller.
The plugin exposes a single method, dispatch(), which takes two arguments:
Forward returns the results of dispatching the requested controller; it is up to the developer to determine what, if anything, to do with those results. One recommendation is to aggregate them in any return value from the invoking controller.
As an example:
1 2 3 4 5 | $foo = $this->forward()->dispatch('foo', array('action' => 'process'));
return array(
'somekey' => $somevalue,
'foo' => $foo,
);
|
The Layout plugin allows for changing layout templates from within controller actions.
It exposes a single method, setTemplate(), which takes one argument:
As an example:
1 | $this->layout()->setTemplate('layout/newlayout');
|
It also implements the __invoke magic method, which allows for even easier setting of the template:
1 | $this->layout('layout/newlayout');
|
The Params plugin allows for accessing parameters in actions from different sources.
It exposes several methods, one for each parameter source:
It also implements the __invoke magic method, which allows for short circuiting to the fromRoute method:
1 2 3 | $this->params()->fromRoute('param', $default);
// or
$this->params('param', $default);
|
When a user sends a POST request (e.g. after submitting a form), their browser will try to protect them from sending the POST again, breaking the back button, causing browser warnings and pop-ups, and sometimes reposting the form. Instead, when receiving a POST, we should store the data in a session container and redirect the user to a GET request.
This plugin can be invoked with two arguments:
When no arguments are provided, the current matched route is used.
Example Usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // Pass in the route/url you want to redirect to after the POST
$prg = $this->prg('/user/register', true);
if ($prg instanceof \Zend\Http\PhpEnvironment\Response) {
// returned a response to redirect us
return $prg;
} elseif ($prg === false) {
// this wasn't a POST request, but there were no params in the flash messenger
// probably this is the first time the form was loaded
return array('form' => $myForm);
}
// $prg is an array containing the POST params from the previous request
$form->setData($prg);
// ... your form processing code here
|
While similar to the standard Post/Redirect/Get Plugin, the File PRG Plugin will work for forms with file inputs. The difference is in the behavior: The File PRG Plugin will interact directly with your form instance and the file inputs, rather than only returning the POST params from the previous request.
By interacting directly with the form, the File PRG Plugin will turn off any file inputs’ required flags for already uploaded files (for a partially valid form state), as well as run the file input filters to move the uploaded files into a new location (configured by the user).
Warning
You must attach a Filter for moving the uploaded files to a new location, such as the RenameUpload Filter, or else your files will be removed upon the redirect.
This plugin can be invoked with three arguments:
Example Usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | $myForm = new Zend\Form\Form('my-form');
$myForm->add(array(
'type' => 'Zend\Form\Element\File',
'name' => 'file',
));
// NOTE: Without a filter to move the file,
// our files will disappear between the requests
$myForm->getInputFilter()->getFilterChain()->attach(
new Zend\Filter\File\RenameUpload(array(
'target' => './data/tmpuploads/file',
'randomize' => true,
))
);
// Pass in the route/url you want to redirect to after the POST
$prg = $this->prg($myForm, '/user/profile-pic', true);
if ($prg instanceof \Zend\Http\PhpEnvironment\Response) {
// Returned a response to redirect us
return $prg;
} elseif ($prg === false) {
// First time the form was loaded
return array('form' => $myForm);
}
// Form was submitted.
// $prg is now an array containing the POST params from the previous request,
// but we don't have to apply it to the form since that has already been done.
// Process the form
if ($form->isValid()) {
// ...Save the form...
return $this->redirect()->toRoute('/user/profile-pic/success');
} else {
// Form not valid, but file uploads might be valid and uploaded
$fileErrors = $form->get('file')->getMessages();
if (empty($fileErrors)) {
$tempFile = $form->get('file')->getValue();
}
}
|
Redirections are quite common operations within applications. If done manually, you will need to do the following steps:
The Redirect plugin does this work for you. It offers two methods:
In each case, the Response object is returned. If you return this immediately, you can effectively short-circuit execution of the request.
Note
This plugin requires that the controller invoking it implements InjectApplicationEvent, and thus has an MvcEvent composed, as it retrieves the router from the event object.
As an example:
1 | return $this->redirect()->toRoute('login-success');
|
Often you may want to generate URLs from route definitions within your controllers – in order to seed the view, generate headers, etc. While the MvcEvent object composes the router, doing so manually would require this workflow:
1 2 | $router = $this->getEvent()->getRouter();
$url = $router->assemble($params, array('name' => 'route-name'));
|
The Url helper makes this slightly more convenient:
1 | $url = $this->url()->fromRoute('route-name', $params);
|
The fromRoute() method is the only public method defined, and has the following signature:
1 | public function fromRoute($route, array $params = array(), array $options = array())
|
Note
This plugin requires that the controller invoking it implements InjectApplicationEvent, and thus has an MvcEvent composed, as it retrieves the router from the event object.
The source code of this file is hosted on GitHub. Everyone can update and fix errors in this document with few clicks - no downloads needed.