Kris Wallsmith

Symfony Guru at opensky.com.
Discussing web development, Symfony and fatherhood.

Oct 20

Oct 19
The truth shall set you free…

The truth shall set you free…


Oct 18


RFC: Mocking Fluent Interfaces in PHPUnit

I sent a pair of pull requests to Sebastian this morning for a very simple change that will make mocking fluent interfaces much easier.

This is how you might mock a fluent interface using PHPUnit 3.5.1:

$mock = $this->getMock('Person');
$mock
  ->expects($this->any())
  ->method('setName')
  ->will($this->returnValue($mock));

I’ve proposed a new returnSelf() method, which would cleanup this code, just a bit:

$mock = $this->getMock('Person');
$mock
  ->expects($this->any())
  ->method('setName')
  ->will($this->returnSelf());

What do you think?


My last presentation during my month of travel was a tech talk on Symfony2 at the L//P offices in Zürich. I did some live coding and demonstrated how to reference a controller from the DIC and unit test that controller using PHPUnit.

My last presentation during my month of travel was a tech talk on Symfony2 at the L//P offices in Zürich. I did some live coding and demonstrated how to reference a controller from the DIC and unit test that controller using PHPUnit.


Oct 17

How to Test a Symfony2 Bundle

The Symfony2 Framework is fully unit tested using PHPUnit. When you create a Symfony2 bundle to share with the community, it’s important that your bundle also be fully unit tested. It’s also important that users be able to run your bundle’s test suite without having to wrap it in a dummy project. This blog post is about how to set that up.

PHPUnit Configuration

Configuration for PHPUnit should be in a file named phpunit.xml.dist in your bundle’s root directory. This file is suffixed .dist since it is the distributed configuration. Users can copy this default configuration to phpunit.xml and make modifications there for their environment. This is necessary when testing bundles, as we’ll see below.

The distributed configuration file should look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./Tests/bootstrap.php">
  <php>
    <!-- <server name="SYMFONY" value="/path/to/symfony" /> -->
  </php>
  <testsuites>
    <testsuite name="FacebookBundle Test Suite">
      <directory suffix="Test.php">./Tests</directory>
    </testsuite>
  </testsuites>
  <filter>
    <whitelist>
      <directory>./</directory>
      <exclude>
        <directory>./Tests</directory>
      </exclude>
    </whitelist>
  </filter>
</phpunit>

This configuration instructs PHPUnit to include a bootstrap file located at the base of your bundles Tests/ directory before running any tests. We’ll take a look at this file below.

The <php> portion of the configuration will define the $_SERVER['SYMFONY'] variable. After copying this file to phpunit.xml, users will need to uncomment this line and enter the actual path to the Symfony2 src/ directory here.

The <testsuites> section of the file tells PHPUnit where to find your test cases. The <filter> section defines a whitelist of files that the test suite is covering, which excludes the test cases themselves.

Autoloading

The purpose of the bootstrap file referenced in the PHPUnit configuration is to initialize autoloading of classes from the Symfony core and from your bundle. The former can be done using the UniversalClassLoader:

require_once $_SERVER['SYMFONY'].'/Symfony/Component/HttpFoundation/UniversalClassLoader.php';

use Symfony\Component\HttpFoundation\UniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespace('Symfony', $_SERVER['SYMFONY']);
$loader->register();

Notice the use of $_SERVER['SYMFONY'], which we defined earlier in the PHPUnit configuration?

Loading of your bundle’s classes is a bit more complicated since we can’t rely on them be installed in any particular directory, but a hack like this will do the trick:

spl_autoload_register(function($class)
{
    if (0 === strpos($class, 'Bundle\\Kris\\FacebookBundle\\')) {
        $path = implode('/', array_slice(explode('\\', $class), 3)).'.php';
        require_once __DIR__.'/../'.$path;
        return true;
    }
});

With this configuration and bootstrap script in place, running your bundle’s test suite is easy as pie:

$ cd ~/Sites/FacebookBundle
$ phpunit

Jul 29

How to create a Symfony2 templating helper

As you get started with Symfony2 you will probably find yourself getting stuck on some tasks that are second-nature to you when developing in symfony 1. One of these will probably be adding a custom helper to your view layer. Hopefully this quick article will clarify that particular process.

Create a helper class

In order to work with the Symfony2 view layer your helper class must implement the HelperInterface interface. This interface is quite simple:

namespace Symfony\Components\Templating\Helper;

interface HelperInterface
{
    function getName();
    function setCharset($charset);
    function getCharset();
}

Most of the time you’ll be extending the abstract base helper class provided in the core, which provides concrete implementations of the latter two methods. This remaining method, getName(), should return the name your helper can be called by from the view layer.

For example, a helper that outputs the Google Analytics tracking code could look something like this:

namespace Application\HelloBundle\Helper;

use Symfony\Components\Templating\Helper\Helper;

class TrackerHelper extends Helper
{
    public function getName()
    {
        return 'tracker';
    }
}

Register your helper

Once you have a concrete helper class you could add it directly to the templating engine using the $engine->set($helper) method. However, Symfony2 provides another, more scalable way to register helpers using the dependency injection container’s tagging mechanism.

To register a service as a templating helper, add a templating.helper tag that includes an alias attribute of the name you would like to use to reference this helper. For example, in hello/config/config.xml:

<services>
    <service id="tracker_helper" class="Application\HelloBundle\Helper\TrackerHelper">
        <tag name="templating.helper" alias="tracker" />
    </service>
</services>

Make it do something!

Now that your helper is registered you can access it in your template files via the templating engine (i.e. $view['tracker']). Let’s make it do something now so this isn’t just academic.

In order to output the correct tracking code, our helper will need to know what site id to use. We can pass this value to our helper’s constructor:

class TrackerHelper extends Helper
{
    protected $profileId;

    public function __construct($profileId)
    {
        $this->profileId = $profileId;
    }

    public function __toString()
    {
        // return tracking code that includes $this->profileId
    }

    // ...
}

Last we just need to configure the constructor parameter in the service container configuration:

<parameters>
    <parameter key="tracker.profile_id">UA-XXXXX-XX</parameter>
</parameters>

<services>
    <service id="tracker_helper" class="Application\HelloBundle\Helper\TrackerHelper">
        <tag name="templating.helper" alias="tracker" />
        <argument>%tracker.profile_id%</argument>
    </service>
</services>

With that, you can now output the tracking code in your template:

<?php echo $view['tracker'] ?>

Voilà! You can now get started developing your own Symfony2 templating helpers.


Feb 15

Blog Post Cut Short

Me < Metro < Paris
I would like to eat a crepe.
What more can I say?

That about sums it up! I’m headed to the symfony live training day, bracing myself for the first of three OSS geek-out days.

I arrived in Paris yesterday morning after flying nine hours up and over the top of the world, getting nary a wink of sleep. This is my second trip to Paris and my first flying solo; so I don’t have my wife’s talented tongue to lean on ( how’s that for imagery?) but am much more comfortable getting around than I would have been otherwise. I know how to read a subway map, buy food and thank people what I hope is graciously.

After I found the hotel yesterday morning, which only took about 1M of exorbitantly priced international AT&T data (read $20), I unpacked and almost immediately went for an aimless walk. I was really just trying to stay away from my bed to help beat this jet lag as quick as possible. I ended up walking about 10k.


Aug 14

Shifting the Sun

When your father dies, say the Irish, you lose your umbrella against bad weather. May his sun be your light, say the Armenians.

When your father dies, say the Welsh, you sink a foot deeper into the earth. May you inherit his light, say the Armenians.

When your father dies, say the Canadians, you run out of excuses. May you inherit his sun, say the Armenians.

When your father dies, say the French, you become your own father. May you stand up in his light, say the Armenians.

When you father dies, say the Indians, he comes back as the thunder. May you inherit his light, say the Armenians.

When your father dies, say the Russians, he takes your childhood with him. May you inherit his light, say the Armenians.

When your father dies, say the English, you join his club you vowed you wouldn’t. May you inherit his sun, say the Armenians.

When your father dies, say the Armenians, your sun shifts forever. And you walk in his light.

Diana Der-Hovanessian

RIP Richard Louis Berkman, 1935-2009