PHPackages                             zenstruck/controller-util - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. zenstruck/controller-util

AbandonedArchivedLibrary[HTTP &amp; Networking](/categories/http)

zenstruck/controller-util
=========================

Utilities for creating Symfony2 responses without dependencies.

v0.6.0(10y ago)407441[1 issues](https://github.com/kbond/ControllerUtil/issues)2MITPHPPHP &gt;=5.3.3

Since Mar 25Pushed 10y ago1 watchersCompare

[ Source](https://github.com/kbond/ControllerUtil)[ Packagist](https://packagist.org/packages/zenstruck/controller-util)[ Docs](http://zenstruck.com/projects/ControllerUtil)[ RSS](/packages/zenstruck-controller-util/feed)WikiDiscussions master Synced 6d ago

READMEChangelog (8)Dependencies (5)Versions (13)Used By (2)

ControllerUtil
==============

[](#controllerutil)

[![Build Status](https://camo.githubusercontent.com/065e920c7645250088e79d624327fa981dacb41d646cf4341273af13ad7d360f/687474703a2f2f696d672e736869656c64732e696f2f7472617669732f6b626f6e642f436f6e74726f6c6c65725574696c2e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/kbond/ControllerUtil)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/422d93c606e2bd8b38a0d360f35147cd6a1f82d415b55be64f7fe0e71700ddc2/687474703a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6b626f6e642f436f6e74726f6c6c65725574696c2e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/kbond/ControllerUtil/)[![Code Coverage](https://camo.githubusercontent.com/62002a6e0a092e0639e75b7593d285c78026113f9c5fea60381b01ed4f072c34/687474703a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f6b626f6e642f436f6e74726f6c6c65725574696c2e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/kbond/ControllerUtil/)[![SensioLabs Insight](https://camo.githubusercontent.com/5af495cd1cb31fa369050c919b62a3e6fc3797f35a935b7342a6539448b50a35/68747470733a2f2f696d672e736869656c64732e696f2f73656e73696f6c6162732f692f34383066396536302d346165302d343665612d623639312d6236366535316161303966342e7376673f7374796c653d666c61742d737175617265)](https://insight.sensiolabs.com/projects/480f9e60-4ae0-46ea-b691-b66e51aa09f4)[![StyleCI](https://camo.githubusercontent.com/f40f32391b70277c507f310bc23ce11ef727ade2d597d9ab23507d0760017616/68747470733a2f2f7374796c6563692e696f2f7265706f732f31373932313233352f736869656c64)](https://styleci.io/repos/17921235)[![Latest Stable Version](https://camo.githubusercontent.com/65088853c86b3e95b11a43792ba4c995385934109e6dd5a3671952e8e649bce1/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7a656e73747275636b2f636f6e74726f6c6c65722d7574696c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/zenstruck/controller-util)[![License](https://camo.githubusercontent.com/15aeae06c37cf731ef49a675b5d6055d09b1550125c685e6c186364912f839d2/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7a656e73747275636b2f636f6e74726f6c6c65722d7574696c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/zenstruck/controller-util)

When creating Symfony2 controllers as services, you often require the same dependencies for every controller.

You often need:

- The router for generating redirects.
- The session for adding flash messages.
- The templating engine for creating views.
- The kernel for forwarding to another controller.
- If using [jms/serializer](https://github.com/schmittjoh/serializer), the serializer.

This library aims to remove those common dependencies by enabling your controllers to return small immutable objects for these tasks. View listeners then take those objects and create the response.

There is a [Symfony2 Bundle](https://github.com/kbond/ZenstruckControllerUtilBundle) and a [Silex Service Provider](https://github.com/kbond/ControllerUtilServiceProvider) available to ease integration into your project.

Usage
-----

[](#usage)

### Forward

[](#forward)

To forward the request to another controller, return the `Zenstruck\ControllerUtil\Forward` object.

```
use Zenstruck\ControllerUtil\Forward;

// ...
public function forwardAction()
{
    return new Forward('another.controller:anotherAction', array('foo' => 'bar'));
}
// ...
```

Arguments:

- `$controller`: the controller to forward to (*required*).
- `$parameters`: an array of parameters to pass to the controller (default: `array()`).

### Redirect

[](#redirect)

To redirect to another route, return the `Zenstruck\ControllerUtil\Redirect` object.

```
use Zenstruck\ControllerUtil\Redirect;

// ...
public function redirectAction()
{
    return new Redirect('my_route');

    // with parameters
    return new Redirect('my_route', array('foo' => 'bar'));
}
// ...
```

Arguments:

- `$route`: the route to redirect to (*required*).
- `$parameters`: an array of parameters required by the route (default: `array()`).
- `$statusCode`: the status code for the response (default: `302`).

### FlashRedirect

[](#flashredirect)

To redirect to another route and add a flash message, return the `Zenstruck\ControllerUtil\FlashRedirect` object.

```
use Zenstruck\ControllerUtil\FlashRedirect;

// ...
public function redirectAction()
{
    return new FlashRedirect('my_route', array('foo' => 'bar'), array('info' => array('Success!'));

    // factory methods
    return FlashRedirect::create('my_route', array('foo' => 'bar'), 'Error', 'error');
    return FlashRedirect::createSimple('my_route', 'Success');
}
// ...
```

Arguments:

- `$route`: the route to redirect to (*required*).
- `$parameters`: an array of parameters required by the route (default: `array()`).
- `$flashes`: an array of flash messages (default: `array()`).
- `$statusCode`: the status code for the response (default: `302`).

**NOTE**: The flashes must be an array in the following format: `array($key => array($message))`. As this can be cumbersome, there are factory methods.

Factory Methods:

- `FlashRedirect::create`:

    Arguments:

    - `$route`: the route to redirect to (*required*).
    - `$parameters`: an array of parameters required by the route (*required*).
    - `$message`: The flash message (*required*).
    - `$type`: The flash type (default: `info`).
    - `$statusCode`: the status code for the response (default: `302`).
- `FlashRedirect::createSimple` (for redirects with no route parameters):

    Arguments:

    - `$route`: the route to redirect to (*required*).
    - `$message`: The flash message (*required*).
    - `$type`: The flash type (default: `info`).
    - `$statusCode`: the status code for the response (default: `302`).

### View

[](#view)

To create a view for your response, return the `Zenstruck\ControllerUtil\View` object. This library has 3 view listeners:

- `TemplatingViewListener`: for rendering views with the Symfony2 templating component.
- `TwigViewListener`: for rendering views with Twig.
- `SerializerViewListener`: for rendering non-html views with [jms/serializer](https://github.com/schmittjoh/serializer).

```
use Zenstruck\ControllerUtil\View;

// ...
public function viewAction()
{
    $object = // ..

    return new View($object, 200);

    // with templates
    return new View($object, 200, 'my_template.html.twig');

    // with an array of fallback templates
    return new View($object, 200, array('my_template.html.twig', 'fallback_template.html.twig'));

    // factory methods
    return View::createCached($object, 86400);
}
// ...
```

Arguments:

- `$data`: the data to pass to the view.
- `$statusCode`: the status code for the response (default: `200`).
- `$template`: the template or an array of templates (default: `null`).
- `$cache`: an array of cache options for the response (default: `array()`).
- `$headers`: an array of response headers (default: `array()`).

Factory Methods:

- `View::createCached`:

    Arguments:

    - `$data`: the data to pass to the view (*required*).
    - `$sharedMaxAge`: the shared max age in seconds (*required*).
    - `$statusCode`: the status code for the response (default: `200`).

**NOTES**:

- When `$template` is an array of templates, the view listener will loop through them and render the first one that exists.
- If no template is provided, you need to have the `SerializerViewListener` enabled and the request must be non-html. Otherwise an error will result.
- If `$data` is not an array, a template is provided, the view listener will convert `$data` to `array('data' => $data)` before passing it to your template.

#### No Content View

[](#no-content-view)

This library has a `NoContentViewListener` which allows your controllers to return an empty View or (if enabled) simply null. The view listener will set a no content response (204).

```
use Zenstruck\ControllerUtil\View;

// ...
public function viewAction()
{
    return new View(null);

    return null; // if enabled
}
// ...
```

### Template

[](#template)

If your views always have a template, you can use the `Zenstruck\ControllerUtil\Template` object for convenience.

```
use Zenstruck\ControllerUtil\Template;

// ...
public function viewAction()
{
    $object = // ..

    return new Template('my_template.html.twig', array('object' => $object));
}
// ...
```

Arguments:

- `$template`: the template or an array of templates (*required*).
- `$parameters`: the parameters to pass to the view (default: `array()`).
- `$statusCode`: the status code for the response (default: `200`).
- `$cache`: an array of cache options for the response (default: `array()`).
- `$headers`: an array of response headers (default: `array()`).

Factory Methods:

- `Template::createCached`:

    Arguments:

    - `$template`: the template or an array of templates (*required*).
    - `$sharedMaxAge`: the shared max age in seconds (*required*).
    - `$parameters`: the parameters to pass to the view (default: `array()`).
    - `$statusCode`: the status code for the response (default: `200`).

Manual installation
-------------------

[](#manual-installation)

It is recommended you use either the [Symfony2 Bundle](https://github.com/kbond/ZenstruckControllerUtilBundle)or the [Silex Service Provider](https://github.com/kbond/ControllerUtilServiceProvider) for including these utilities in your project.

If you are doing something custom using the Symfony2 Event Dispatcher, you can register the listeners manually:

```
// add the HasFlashesListener
$eventDispatcher->addListener(
    KernelEvents::VIEW,
    array(new HasFlashesListener($flashBag), 'onKernelView'),
    10 // before other events
);

// add the RedirectListener
$eventDispatcher->addListener(
    KernelEvents::VIEW,
    array(new RedirectListener($urlGenerator), 'onKernelView')
);

// add the ForwardListener
$eventDispatcher->addListener(
    KernelEvents::VIEW,
    array(new ForwardListener(), 'onKernelView')
);

// add the TwigViewListener
$eventDispatcher->addListener(
    KernelEvents::VIEW,
    array(new TwigViewListener($twigEnvironment), 'onKernelView')
);

// add the TemplatingViewListener
$eventDispatcher->addListener(
    KernelEvents::VIEW,
    array(new TemplatingViewListener($templating), 'onKernelView')
);

// add the NoContentViewListener
$eventDispatcher->addListener(
    KernelEvents::VIEW,
    array(new NoContentViewListener(true /* false to force an empty view and not allow null */), 'onKernelView'),
    7 // before other events
);

// add the SerializerViewListener
$eventDispatcher->addListener(
    KernelEvents::VIEW,
    array(new SerializerViewListener($serializer), 'onKernelView'),
    5 // before other events
);
```

**NOTES**:

- Notice the priority on the `HasFlashesListener`, `NoContentViewListener` and `SerializerViewListener`. These need to be triggered before the other listeners.
- You should only use either the `TemplatingViewListener` or `TwigViewListener` - not both.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity24

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 98.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~90 days

Recently: every ~75 days

Total

8

Last Release

3806d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/707369cc916e0ea1aacbf077dcba464f611cef879f024d8944311a54a15224b3?d=identicon)[kbond](/maintainers/kbond)

---

Top Contributors

[![kbond](https://avatars.githubusercontent.com/u/127811?v=4)](https://github.com/kbond "kbond (55 commits)")[![pborreli](https://avatars.githubusercontent.com/u/77759?v=4)](https://github.com/pborreli "pborreli (1 commits)")

---

Tags

responsesymfonyrestserializerSymfony2controllersilex

### Embed Badge

![Health badge](/badges/zenstruck-controller-util/health.svg)

```
[![Health](https://phpackages.com/badges/zenstruck-controller-util/health.svg)](https://phpackages.com/packages/zenstruck-controller-util)
```

###  Alternatives

[api-platform/core

Build a fully-featured hypermedia or GraphQL API in minutes!

2.6k48.1M236](/packages/api-platform-core)[nilportugues/jsonapi-bundle

Symfony 2 &amp; 3 JSON API Transformer Package

11446.0k](/packages/nilportugues-jsonapi-bundle)[xabbuh/panda-bundle

integration of the Panda encoding services into the Symfony2 Framework

10174.6k](/packages/xabbuh-panda-bundle)[mediamonks/rest-api

MediaMonks Rest API

1351.3k1](/packages/mediamonks-rest-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
