Using ZF2 Forms with Twig

Following on from looking at how to integrate Zend Framework 2 forms into Slim Framework, let's look at the changes required if you also happen to want to use Twig.

When it comes to rendering the form, we would want our template to look like this:

    <form method="POST" role="form">
        <div class="form-group">
            {{ formRow(form.get('email')) }}
        </div>
        {{ formElement(form.get('submit')) }}
    </form>

The ZF2 view helpers, formRow and formElement now look like Twig functions, however we don't want to have to rewrite all our ZF2 view helpers into Twig. Fortunately, Twig supports the concept of a undefined function callback is called whenever Twig encounters a function that it doesn't know how to call. We can use this to proxy through to the Zend\View system and get it to render the ZF2 view helpers.

Let's look at how we do this.

Starting with the work in the previous article, we merely need to change the view layer. That is, we don't need a custom PHP view (\RKA\View), but instead use the Slim-Views Twig component.

To add Twig to a Slim project we update composer.json and add "twig/twig": "1.16.*" and "slim/views": "0.1.*" to the require section and then run composer update.

We then update index.php to add the view class when instantiating the Slim and configure it.:

$app = new \Slim\Slim([
    'view' => new \Slim\Views\Twig()
]);

// Configure Twig
$view = $app->view();
$view->parserOptions = [
    'debug' => true,
    'cache' => false,
];
$view->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
);

Now, whenever we call $app->render(), Twig will be used. The view templates have a .twig extension, so we rename home.php to home.twig and it's rendered like this:

$app->render('home.twig', [
    'form' => $form
]);

To integrate the ZF2 Form view helpers without having to rewrite them all as Twig extensions, we just need to register an undefined callback function that uses Zend Framework 2's PhpRenderer to render the view helper.

This is done with a few lines in index.php:

$viewHelperManager = $app->serviceManager->get('ViewHelperManager');
$renderer = new \Zend\View\Renderer\PhpRenderer();
$renderer->setHelperPluginManager($viewHelperManager);

$view->getInstance()->registerUndefinedFunctionCallback(
    function ($name) use ($viewHelperManager, $renderer) {
        if (!$viewHelperManager->has($name)) {
            return false;
        }

        $callable = [$renderer->plugin($name), '__invoke'];
        $options  = ['is_safe' => ['html']];
        return new \Twig_SimpleFunction(null, $callable, $options);
    }
);

Let's break this down.

Firstly, we create a PhpRenderer and set the helper plugin manager to ViewHelperManager that's already defined in the service manager.

We can access the underlying Twig_Environment object using $view->getInstance() and then call registerUndefinedFunctionCallback with a closure for our callback.

The callback code is this bit:

    function ($name) use ($viewHelperManager, $renderer) {
        if (!$viewHelperManager->has($name)) {
            return false;
        }

        $callable = [$renderer->plugin($name), '__invoke'];
        $options  = ['is_safe' => ['html']];
        return new \Twig_SimpleFunction(null, $callable, $options);
    }

Within the callback we check the ViewHelperManager to see if we have a view helper that we can call. If we don't then we return false so that Twig can try a difference undefined function callback in its list.

If we do know about this view helper, then we instantiate a Twig_SimpleFunction that will call the __invoke method of the view helper which we retrieve via the plugin method of the renderer. Note that we also tell Twig that our view helper is safe to use with HTML so it doesn't escape the HTML tags created by the view helper.

That's all there is to it.

The code that's shown here is on GitHub in the twig branch of the slim-zendform project, so you can download it and play around yourself.

Sending attachments in multipart emails with Zend\Mail

I've written before about how to send an HTML email with a text alternative in Zend\Mail, but recently needed to send an attachment with my multipart email.

With help from various sources on the Internet, this is how to do it.

use Zend\Mail\Message;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;
use Zend\Mime\Mime;
use Zend\Mail\Transport\Sendmail;

function sendEmail($to, $from, $subject, $html, $text, $attachments = null)
{
    $message = new Message();

    $message->addTo($to);
    $message->addFrom($from);
    $message->setSubject($subject);

    // HTML part
    $htmlPart           = new MimePart($html);
    $htmlPart->encoding = Mime::ENCODING_QUOTEDPRINTABLE;
    $htmlPart->type     = "text/html; charset=UTF-8";

    // Plain text part
    $textPart           = new MimePart($text);
    $textPart->encoding = Mime::ENCODING_QUOTEDPRINTABLE;
    $textPart->type     = "text/plain; charset=UTF-8";

    $body = new MimeMessage();
    if ($attachments) {
        // With attachments, we need a multipart/related email. First part
        // is itself a multipart/alternative message        
        $content = new MimeMessage();
        $content->addPart($textPart);
        $content->addPart($htmlPart);

        $contentPart = new MimePart($content->generateMessage());
        $contentPart->type = "multipart/alternative;\n boundary=\"" .
            $content->getMime()->boundary() . '"';

        $body->addPart($contentPart);
        $messageType = 'multipart/related';

        // Add each attachment
        foreach ($attachments as $thisAttachment) {
            $attachment = new MimePart($thisAttachment['content']);
            $attachment->filename    = $thisAttachment['filename'];
            $attachment->type        = Mime::TYPE_OCTETSTREAM;
            $attachment->encoding    = Mime::ENCODING_BASE64;
            $attachment->disposition = Mime::DISPOSITION_ATTACHMENT;

            $body->addPart($attachment);
        }

    } else {
        // No attachments, just add the two textual parts to the body
        $body->setParts(array($textPart, $htmlPart));
        $messageType = 'multipart/alternative';
    }

    // attach the body to the message and set the content-type
    $message->setBody($body);
    $message->getHeaders()->get('content-type')->setType($messageType);
    $message->setEncoding('UTF-8');

    $transport = new Sendmail();
    $transport->send($message);
}

Let's look at some key parts.

The text of the email

The HTML and plain text parts of the email are treated the same. We create a Zend\Mime\Part and set the encoding and type. For HTML, it looks like this:

    $htmlPart           = new MimePart($html);
    $htmlPart->encoding = Mime::ENCODING_QUOTEDPRINTABLE;
    $htmlPart->type     = "text/html; charset=UTF-8";

Note that if your text is UTF-8, then you must set this in the part's type, as it is not passed through from the message level when set there.

Creating the multipart/alternative

If we have attachments, then we need to create a new multipart/alternative Zend\Mime\Message for the first part which contains the HTML and plain text parts:

        $content = new MimeMessage();
        $content->addPart($textPart);
        $content->addPart($htmlPart);

        $contentPart = new MimePart($content->generateMessage());
        $contentPart->type = "multipart/alternative;\n boundary=\"" .
            $content->getMime()->boundary() . '"';

        $body->addPart($contentPart);
        $messageType = 'multipart/related';

The important section here is that $contentPart is created with the generated message from the $content object which is the text of the two parts with the correct mime sections around them. We then need to set the type to mulipart/alternative and also define the boundary as the auto-generated identifier from $content.

Adding attachments

Attachments are similar to adding text:

            $attachment = new MimePart($thisAttachment['file_data']);
            $attachment->filename    = $thisAttachment['filename'];
            $attachment->type        = Mime::TYPE_OCTETSTREAM;
            $attachment->encoding    = Mime::ENCODING_BASE64;
            $attachment->disposition = Mime::DISPOSITION_ATTACHMENT;

            $body->addPart($attachment);

Again, you we create a Zend\Mime\Part for each attachment containing the raw file data. We also need to set the filename property along with the type, encoding and disposition.

Setting content-type

If we don't have attachments, then the message type is 'multipart/alternative', so that's set in the other half of the if/else. We can then add the body to the message and set its content-type:

    $message->setBody($body);
    $message->getHeaders()->get('content-type')->setType($messageType);
    $message->setEncoding('UTF-8');

We're all done, so we can send the email.

In this code, I'm using the Sendmail transport, but obviously Zend\Mail supports other options, including SMTP.

Throw an exception when simplexml_load_string fails

I keep having to look up how to stop the warning that are emitted when simplexml_load_string & simplexml_load_file fail, so this time I've written the world's simplest little class to take care of it for me from now on:

<?php

namespace Rka;

use UnexpectedValueException;

class Xml
{
    /**
     * Load an XML String and convert any warnings to an exception
     *
     * @param string  $string
     * @param string $class_name
     * @param int $options
     * @param string $ns
     * @param bool $is_prefix
     *
     * @throws UnexpectedValueException
     *
     * @return SimpleXMLElement
     */
    public static function loadXMLString(
        $string,
        $class_name = "SimpleXMLElement",
        $options = 0,
        $ns = "",
        $is_prefix = false
    ) {
        $previous = libxml_use_internal_errors(true);

        $xml = simplexml_load_string($string, $class_name, $options, $ns,
                 $is_prefix);

        if (!$xml) {
            $errors = self::getXMLErrorString();
            libxml_use_internal_errors($previous);
            throw new UnexpectedValueException($errors);
        }

        libxml_use_internal_errors($previous);
        return $xml;
    }

    /**
     * Load an XML File and convert any warnings to an exception
     *
     * @param string  $string
     * @param string $class_name
     * @param int $options
     * @param string $ns
     * @param bool $is_prefix
     *
     * @throws UnexpectedValueException
     *
     * @return SimpleXMLElement
     */
    public static function loadXMLFile(
        $string,
        $class_name = "SimpleXMLElement",
        $options = 0,
        $ns = "",
        $is_prefix = false
    ) {
        $previous = libxml_use_internal_errors(true);

        $xml = simplexml_load_file($string, $class_name, $options, $ns,
                 $is_prefix);

        if (!$xml) {
            $errors = self::getXMLErrorString();
            libxml_use_internal_errors($previous);
            throw new UnexpectedValueException($errors);
        }

        libxml_use_internal_errors($previous);
        return $xml;
    }

    /**
     * Helper method to format the XML errors into a string.
     *
     * @return string
     */
    protected static function getXMLErrorString()
    {
        $message = '';
        foreach (libxml_get_errors() as $error) {
            $message .= trim($error->message)
              . " on line: $error->line, column: $error->column.\n";
        }
        libxml_clear_errors();
        return trim($message);
    }
}

Update: The code has been updated based on the comments below. Thanks!

Redirecting in Slim Middleware

I recently ran into a problem with calling redirect() in a Slim framework middleware class, so I thought I'd better document the solution so that I remember in future!

The authentication middleware looks roughly like this:

class Authentication extends \Slim\Middleware
{
    public function call()
    {
        if (!$this->isLoggedIn()) {
            $app = \Slim\Slim::getInstance();
            $app->redirect($app->urlFor('login'));
        }

        $this->next->call();
    }

    // other methods...
}

The problem is that you can't call $app->redirect() in Middleware as redirect() is designed to only run in application route callbacks and Middleware should only act on the request and response objects.

This is because the app's redirect() method calls through to stop() which throws a Stop exception which is intended to be caught by the app's call() method. However, if this exception is thrown in middleware, then it isn't caught by call() and the redirect doesn't work. What's weird is that it works on some (most?) web servers but not all.

The correct way to redirect in middleware, use the Response's redirect() method instead like this:

class Authentication extends \Slim\Middleware
{
    public function call()
    {
        if (!$this->isLoggedIn()) {
            $app = \Slim\Slim::getInstance();
            return $app->response()->redirect($app->urlFor('login'));
        }

        $this->next->call();
    }

    // other methods...
}

Note that we return the result of $response->redirect() so that the next item in the chain isn't called.

Integrating ZF2 forms into Slim

Let's say that you want to use Zend Framework 2's Form component outside of ZF2 itself. In this case, a Slim application.

It turns out that Composer makes this quite easy, though there's quite a lot of code involved, so this is a long article.

Start with a really simple Slim Application.

index.php:

require 'vendor/autoload.php';
$app = new \Slim\Slim();

$app->map('/', function () use ($app) {
    $app->render('home.php', array(
        'form' => $form
    ));
})->via('GET', 'POST');

$app->run();

templates/home.php:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
</head>

<body role="document">
  <div class="container">
    <h1 class="content-subhead">Using ZF2 Forms with Slim</h1>
  </div>
</body>
</html>

and of course, composer.json:

{
    "require": {
        "slim/slim": "2.*",
    }
}

Given this starting point, we can now add Zend\Form.

Firstly, we update composer.json:

{
    "require": {
        "slim/slim": "2.*",
        "zendframework/zend-form": "2.3.*",
        "zendframework/zend-servicemanager": "2.3.*",
        "zendframework/zend-i18n": "2.3.*",
        "zendframework/zend-view": "2.3.*",
        "zendframework/zend-escaper": "2.3.*"
    },
    "autoload": {
        "psr-4": {
            "RKA\\" : "RKA"
        }
    }
}

I've also set up the RKA namespace as we'll have to create some classes ourselves.

These are minimum set of components for it all to work. If you do your own rendering, then you don't need zend-view or zend-escaper. You'll then only need zend-i18n for some validators and filters.

When you run composer update, you'll see that the following ZF2 components are installed for you:

  • Zend\StdLib
  • Zend\Validator
  • Zend\Filter
  • Zend\InputFilter
  • Zend\Form
  • Zend\Loader
  • Zend\EventManager
  • Zend\View
  • Zend\I18n
  • Zend\ServiceManager
  • Zend\Escaper

Other than EventManger which is required by View, this doesn't seem an unreasonable list to me.

As, we'll probably want to override the default validation messages and add our own validators & filters, it's worth spending the time setting up our own instance of Zend\ServiceManager and using that to instantiate the form for us.

Configuring the service manager with the relevant plugin managers is usually done by Zend\Mvc & Zend\ModuleManager, so we'll simplify and create a single class called ServiceManagerConfigurator. This is the most complicated part of the entire thing and looks like this:

RKA\ServiceManagerConfigurator:

namespace RKA;

use Zend\ServiceManager\Config as ServiceConfig;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ServiceManagerConfigurator
{
    // List of plugin managers to register (key name => class name)
    public $pluginManagers = [
        'FilterManager'      => 'Zend\Filter\FilterPluginManager',
        'FormElementManager' => 'Zend\Form\FormElementManager',
        'InputFilterManager' => 'Zend\InputFilter\InputFilterPluginManager',
        'ValidatorManager'   => 'Zend\Validator\ValidatorPluginManager',
        'ViewHelperManager'  => 'Zend\View\HelperPluginManager',
    ];
    
    // Keys to look for in the config array (config key name => sm key name)
    public $configKeys = [
        'validators'      => 'ValidatorManager',
        'filters'         => 'FilterManager',
        'form_elements'   => 'FormElementManager',
        'input_filters'   => 'InputFilterManager',
        'view_helpers'    => 'ViewHelperManager',
    ];

    // Main method that gives us back a configured ServiceManager
    public function createServiceManager(array $config)
    {
        // create ServiceManager
        $serviceManager = new ServiceManager();

        // set an initializer for ServiceLocatorAwareInterface
        $serviceManager->addInitializer(
            function ($instance, ServiceLocatorInterface $serviceLocator) {
                if ($instance instanceof ServiceLocatorAwareInterface) {
                    $instance->setServiceLocator($serviceLocator);
                }
            }
        );
        // add $serviceManger to the config keys so we can configure it
        $this->configKeys = ['service_manager' => $serviceManager] 
                            + $this->configKeys;

        // add the pluginManagers to the ServiceManager
        foreach ($this->pluginManagers as $key => $className) {
            $serviceManager->setInvokableClass($key, $className);
        }

        // add Zend\Form's view helpers to the ViewHelperManager
        $viewHelperManager = $serviceManager->get('ViewHelperManager');
        $vhConfig = new \Zend\Form\View\HelperConfig;
        $vhConfig->configureServiceManager($viewHelperManager);

        // apply configuration
        $this->applyConfig($serviceManager, $config);
        return $serviceManager;
    }

    // Helper method to apply config to the service manager and all plugins
    public function applyConfig($serviceManager, $config)
    {
        foreach ($this->configKeys as $keyName => $thisManager) {

            $smConfig = array();
            if (isset($config[$keyName]) && is_array($config[$keyName])) {
                $smConfig = $config[$keyName];
            }
            
            // Get this service manager from the main service manager if it
            // isn't an instance already
            if (!$thisManager instanceof ServiceManager) {
                $thisManager = $serviceManager->get($thisManager);
            }

            // Apply the config to this service manager
            $serviceConfig = new ServiceConfig($smConfig);
            $serviceConfig->configureServiceManager($thisManager);
        }
    }
}

I've commented the code so that hopefully, it's fairly easy to follow.

The key method is createServiceManager which will instantiate a ServiceManager object, add the plugin managers and other bits and bobs before calling the helper method applyConfig which will do the custom configuration.

To use it, we update our index.php:

index.php:

$app = new \Slim\Slim();

$config = [
    'validators' => array(
        'invokables' => array(
            'email-address' => 'RKA\Validator\EmailAddress',
            'string-length' => 'RKA\Validator\StringLength',
            // etc.
        ),
    ),
    'form_elements' => array(
        'invokables' => array(
            'RKA\ExampleForm'  => 'RKA\ExampleForm',
        ),
    ),

];

$smConfigurator = new RKA\ServiceManagerConfigurator();
$app->serviceManager = $smConfigurator->createServiceManager($config);
$app->view(new RKA\View());

// continue with $app->map() calls

We firstly set up the config that we want. In this case, I want to add my custom validators and then I add the form we want to use. Obviously, if we had custom filters, form elements or view helpers we could also add those too. Also, although I'm using invokables, you could also use factories if any of the classes you were adding had dependencies that needed adding.

The form is defined as any other Zend\Form is. In this case, I created a separate class called RKA\ExampleForm, but we could equally have used the factory creation.

RKA\ExampleForm:

namespace RKA;

use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;

class ExampleForm extends Form implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add([
            'name' => 'email',
            'options' => [
                'label' => 'Email address',
            ],
            'attributes' => [
                'id'       => 'email',
                'class'    => 'form-control',
                'required' => 'required',
            ],
        ]);

        $this->add([
            'name' => 'submit',
            'type' => 'button',
            'options' => [
                'label' => 'Go!',
            ],
            'attributes' => [
                'class' => 'btn btn-default',
            ],
        ]);
    }

    public function getInputFilterSpecification()
    {
        return [
            'email' => [
                'required' => true,
                'filters'  => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags'],
                ],
                'validators' => [
                    ['name' => 'EmailAddress'],
                ],
            ],
        ];
    }
}

Nothing complicated is going on here. We add two elements to the form and then define some validation for the email element.

To use the form, we update our handler for '/':

$app->map('/', function () use ($app) {
    $formElementManager = $app->serviceManager->get('FormElementManager');
    $form = $formElementManager->get("RKA\ExampleForm");

    if ($app->request->isPost()) {
        $data = $app->request->post();
        $form->setData($data);
        $isValid = $form->isValid();
        if ($form->isValid()) {
            echo "Success!";
            exit;
        }
    }

    $app->render('home.php', array(
        'form' => $form
    ));
})->via('GET', 'POST');

We grab the $formElementManager from the service manager and then grab our example form form there. If the request is a POST, then we set the posted data to the form and test for validity. On success, we would probably redirect. Finally we render our view template, passing the form to it.

We render the form within the view template using Zend\Form's formRow view helpers to render the label, element and errors and label in one go for us, though we could have used the formLabel, formElement and formElementErrors view helpers separately:

templates/home.php:

    <!-- ... -->
    <h1 class="content-subhead">Using ZF2 Forms with Slim</h1>
      
      <form method="POST" role="form">
          <div class="form-group">
              <?= $this->formRow($form->get('email')) ?>
          </div>
          <?= $this->formElement($form->get('submit')) ?>
      </form>

    <!-- ... -->        
 

Finally, we have to extends Slim\View to integrate ZF2's view helper system with it. This requires implementing the Zend\View\Renderer\RendererInterface and also writing a __call() method:

Rka\View:

namespace RKA;

use Slim\Slim;
use Zend\View\Renderer\RendererInterface;

class View extends \Slim\View implements RendererInterface
{
    protected $viewHelpers;
    protected $helperCache;

    public function __construct()
    {
        parent::__construct();

        $app = Slim::getInstance();
        $sm = $app->serviceManager;
        $this->viewHelpers = $sm->get('ViewHelperManager');
    }

    public function plugin($name, array $options = null)
    {
        $helper = $this->viewHelpers->get($name, $options);
        $helper->setView($this);
        return $helper;
    }

    public function __call($method, $argv)
    {
        if (!isset($this->helperCache[$method])) {
            $this->helperCache[$method] = $this->plugin($method);
        }
        if (is_callable($this->helperCache[$method])) {
            return call_user_func_array($this->helperCache[$method], $argv);
        }
        return $this->helperCache[$method];

    }

    // Required by RendererInterface
    public function render($template, $data = null)
    {
        return parent::render($template, $data);
    }

    public function getEngine()
    {
        return $this;
    }
    
    public function setResolver(\Zend\View\Resolver\ResolverInterface $resolver)
    {
        return $this;
    }
}

One undocumented feature of the formElement view helper is that it looks for a method called plugin in the View class, so I created one for it!

The final result looks like:

Slim zendform

That's it. The code that's shown here is on GitHub in the slim-zendform project, so you can download it and play around yourself.

Globally overriding validation messages for ZF2 forms

One thing that I always do when creating a Zend Framework 2 form is override the validation messages for a number of validators – EmailAddress in particular.

I recently decided that I should probably sort this one out once and be done with it. Turns out that it's quite easy assuming that you use the FormElementManger to instantiate your forms.

All that I need to do is create my own validator classes that extend the Zend Framework ones and just set new message templates. This is what EmailAddress looks like:

namespace RKA\Validator;

use Zend\Validator\EmailAddress as BaseEmailAddress;

class EmailAddress extends BaseEmailAddress
{
    protected $messageTemplates = array(
        self::INVALID            => "Invalid type given. String expected",
        self::INVALID_FORMAT     => "Invalid email address",
        self::INVALID_HOSTNAME   => "Invalid email address",
        self::INVALID_MX_RECORD  => "Invalid email address",
        self::INVALID_SEGMENT    => "Invalid email address",
        self::DOT_ATOM           => "Invalid email address",
        self::QUOTED_STRING      => "Invalid email address",
        self::INVALID_LOCAL_PART => "Invalid email address",
        self::LENGTH_EXCEEDED    => "Email address is too long",
    );
}

To ensure that the ValidatorPluginManager uses the new validator in place of the default one, we override in module.config.php:

    'validators' => [
        'invokables' => [
            'email-address' => 'RKA\Validator\EmailAddress',
            'string-length' => 'RKA\Validator\StringLength',
            // etc.
        ],
    ],

Now, whenever you create a form with input filter that uses FormAbstractServiceFactory or via a config array with the Form\Factory as set up in my last post, then the new validator is picked up (assuming you use the short name).

If you create your forms via a class, then you should use the FormElementManager like this.

Firstly, create your form:

namespace RKA\Form;

use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;

class ExampleForm extends Form implements InputFilterProviderInterface
{
    public function init()
    {
        $this->add([
            'name' => 'email',
            'type' => 'text',
            'options' => [
                'label' => 'Email address',
            ],
            'attributes' => [
                'class'    => 'form-control',
                'required' => 'required',
            ],
        ]);

        $this->add([
            'name' => 'submit',
            'type' => 'button',
            'options' => [
                'label' => 'Go!',
            ],
            'attributes' => [
                'class' => 'btn btn-default',
            ],
        ]);
    }

    public function getInputFilterSpecification()
    {
        return [
            'email' => [
                'required' => true,
                'filters'  => [
                    ['name' => 'StringTrim'],
                    ['name' => 'StripTags'],
                ],
                'validators' => [
                    ['name' => 'EmailAddress'],
                ],
            ],
        ];
    }
}

Note that in getInputFilterSpecification we use the service manager key names for each validator name. The ones that are shipped with ZF2 are listed in the ValidatorPluginManager.

Now register it with the FormElementManager in module.config.php:

    'form_elements' => [
        'invokables' => [
            'RKA\ExampleForm'  => 'RKA\Form\ExampleForm',
        ],
    ],

You can then instantiate it in your controller via the main service locator:

    // in my controller
    public function getExampleForm()
    {
        $formManager = $this->getServiceLocator()->get('FormElementManager');
        return $formManager->get('RKA\ExampleForm');
    }

In addition to forms, you can also register your own fieldsets and elements under the 'form_elements' key and then use them within your forms.

Creating a ZF2 form from config

I have a requirement to create a Zend\Form from a dynamically created array which means that I can't use the FormAbstractServiceFactory and so will use Zend\Form\Factory directly.

If you need to override any form elements, validators or add new ones, then you'll need the correct plugin managers for the factory. The way to set this up is like this:

$factory = new Factory();
$formElements = $this->serviceLocator->get('FormElementManager');
$factory->setFormElementManager($formElements);
$inputFilters = $this->serviceLocator->get('InputFilterManager');
$factory->getInputFilterFactory()->setInputFilterManager($inputFilters); 

Your $factory is now configured and so you can create a form like this:

$formConfig = [
    'elements' => [
        [
            'spec' => [
                'name' => 'name',
                'options' => [
                    'label' => 'Your name',
                ],
                'attributes' => [
                    'type' => 'text',
                    'class' => 'form-control',
                    'required' => 'required',
                ],
            ],
        ],
        [
            'spec' => [
                'name' => 'email',
                'options' => [
                    'label' => 'Your email address',
                ],
                'attributes' => [
                    'type' => 'text',
                    'class' => 'form-control',
                    'required' => 'required',
                ],
            ],
        ],
    ],
    'input_filter' => [
        'name' => [
            'name'       => 'name',
            'required'   => true,
            'validators' => [
                [
                    'name' => 'not_empty',
                ],
                [
                    'name' => 'string_length',
                    'options' => [
                        'max' => 30,
                    ],
                ],
            ],
        ],
        'email' => [
            'name'       => 'email',
            'required'   => true,
            'validators' => [
                [
                    'name' => 'not_empty',
                ],
                [
                    'name' => 'email_address',
                ],
            ],
        ],
    ],
];

$form = $factory->createForm($formSpec);

View status of all Vagrant environments

I've just upgraded to Vagrant version 1.6, and vagrant global-status is possibly my favourite new feature.

This command lists all currently up Vagrant environments wherever they may be on your computer:

$ vagrant global-status

id       name    provider   state   directory                                         
--------------------------------------------------------------------------------------
dbc7770  joindin virtualbox running /Users/rob/www/thirdparty/joindin-vm              
0683c7a  default virtualbox running /Users/rob/www/thirdparty/joindin-zs7 
 
The above shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date. To interact with any of the machines, you can go to
that directory and run Vagrant, or you can use the ID directly
with Vagrant commands from any directory. For example:
"vagrant destroy 1a2b3c4d"

As you can see by the helpful information message, you can then pass the id to any of the usual Vagrant commands in order to work with that Vagrant install rather than changing directory first.

I tend to use this to halt VMs that I've left running by accident! i.e.

$ vagrant halt 0683c7a

All in all, a very useful feature!

Prefixing every key in a hash ref in Perl

I needed to prepend some text to every element in a Perl hash ref, so I came up with:

$hashref->{"prefix_$_"} = delete($hashref->{$_}) foreach (keys %$hashref);

which prefixes each key of $hashref with "prefix_".

After talking it over with Cliff, he was concerned with modifying the list in place while simultaneously iterating over it and suggested this solution:

%$hashref = map { +"prefix_$_" => $hashref->{$_} } keys %$hashref;

One interesting thing about this solution is the requirement for a unary "+" in map in order to help Perl work out whether we are using map BLOCK LIST or map EXPR, LIST as in this case it guesses wrong without it. from the documentation:

{ starts both hash references and blocks, so map { ... could be either the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look ahead for the closing } it has to take a guess at which it's dealing with based on what it finds just after the {. Usually it gets it right, but if it doesn't it won't realize something is wrong until it gets to the } and encounters the missing (or unexpected) comma. The syntax error will be reported close to the }, but you'll need to change something near the { such as using a unary + to give Perl some help

Of course, it's knowing the quirks like this that makes you comfortable in a given language, in the same way that good JavaScript developers know about 53 bit integers.

Z-Ray for Zend Server 7

I see that Zend Server 7 has now been released.

I've been running the beta for all my development work for a while now and the main reason is the new Z-Ray feature. Z-Ray is a bar that is injected into the bottom of your page showing lots of useful information.

This is what it looks like in its closed state when run on my development version of joind.in:

Z ray1

At a glance, I can see that this page's performance is acceptable, there's a notice that I need to look at and that 11 database queries were executed.

Continue reading