Feature flags with Symfony2

Feature flags is a really common design in modern web applications and is heavily used by startups. It permits you to enable/disable features for some users or groups of users. It’s really handy if you want to deploy to production a feature for testing purpose in order to have data on how your infrastructure reacts in a live environment.

Let’s have some fun and try to implements a simple feature flags design in your Symfony2 project without writing too much lines of PHP. Sure, we will use the as complex as powerful Security component for that. I won’t dig deep inside it, so you’ll better be well versed about roles and roles hierarchy.

What we want for this project is three types of feature groups: ‘alpha’, ‘beta’ and ‘prod’. I want the admins of my website to have access to the alpha/unstable features, the beta testing group to the beta features and all the oser users to all the rest of my application.

We can express this by using role hierarchy:


security:
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_USER,ROLE_ADMIN,ROLE_ALLOWED_TO_SWITCH

          FEATURE_ALPHA: FEATURE_BETA, FEATURE_SUPER_SECRET
          FEATURE_BETA: FEATURE_PROD, FEATURE_FOOBAR
          FEATURE_PROD: FEATURE_FOO, FEATURE_BAR ```

Thus, anyone whom is granted the FEATURE_ALPHA role will have access to all
the features and the other groups won’t have access to the “lower” features.

This is a rad way of defining who have access to what, but currently,
it’s not supported by the SecurityBundle because only roles prefixed by
ROLE_ are supported by the current voter.

So, we need to define a new voter that supports the newly created FEATURE_*
roles. Is it complicated? Hell no. Add this to your bundle xml configuration:

“` xml Acme/Bundle/AwesomeBundle/Resources/config/config.xml

FEATURE_


This simple piece of xml will register a new voter based on the actual role
hierarchy. The difference is that this voter will be specialised in the
`FEATURE_` prefixed roles.

Now, we need to specify in our user class how the roles will be distributed:

``` php
<?php
// You can implement your own logic there, be inventive.
public function getRoles()
{
    if ($this->isAdmin) {
        return array('ROLE_ADMIN', 'FEATURE_ALPHA');
    }

    if ($this->isBetaTester) {
        return array('ROLE_ADMIN', 'FEATURE_BETA');
    }

    return array('ROLE_USER', 'FEATURE_PROD');
}

From now on, the user class will be able to tell wich roles he has, and the
Security context will be able to vote on them. The only thing left to do is to
“secure” parts of your application.

In your templates:


{% if app.security.isGranted('FEATURE_SUPER_SECRET')) %}
    {# bla bla bla #}
{% endif %}

or in your controllers:

<?php
public function indexAction()
{
    if ($this->get('security.context')->isGranted('FEATURE_SUPER_SECRET')) {
        // do stuff
    }
}

or your routes thanks to the built-in firewall:

yaml app/config/security.yml
security:
access_control:
-
path: ^/my/route/to/my/feature.*$
roles: [FEATURE_SUPER_SECRET]

Here we are! You enabled feature flags in your project with a few lines of PHP
and 5 lines of XML. Have fun!

Back from SfDay 2011 Cologne

I’m now back to my daily work at SensioLabs after some days spent at Cologne, mostly for the Symfony Day 2011. It was truly great to be there. I had the chance to put faces on twitter nicknames and to talk in front of the crowd. I was a bit nervous and wasn’t as relaxed as I would liked to be. I will try to work on my english pronunciation for the next times.

Many thanks to the SensioLabs Deutschland & Interlution team, it was really a nice moment.

Oh, and here are the slides of my talk.

I assure you, it’s open

Kids. Backuping your data is great. But assure you that your backups
also contain your database. I’ve lost all the posts of this blogs and
much more. Nothing to say that I was really pissed off.

I wanted to recreate this blog from scratch but got distract by other
things. After a few months of procrastinating and slapping myself for
not having a place to write, I found a great theme based on twitter
bootstrap for wordpress and decided to give it a go. I’m pretty happy
with that.

Let’s hope I’ll have the strength to write some interesting articles.

Oh, I’m currently concerned by twitter/facebook tracking on the web and
won’t add “tweet this” or “like” button but I will, for now, conserve
the Google analytics tracking script and the feedburner thingy.

P.S : The picture and the post’s title come from the awesome
Clerks and Clerks
2
movies. If you haven’t seen
them, it’s never too late.

Semantic Coding?

Don’t worry. Semantic coding is not a new concept. Actually, you’re
already doing it each time you code. At least, I hope for you and your
teammates. The principle of semantic coding is simple and is a great
part of what we all name “code readability”.

Look at those 2 pieces of code:

<?php
class A
{
    public function A($a, $b)
    {
        return $a + $b;
    }

    public function B($a, $b)
    {
        return $a - $b;
    }

    public function C($a, $b)
    {
        return $a / $b;
    }

    public function D($a, $b)
    {
        return $a * $b;
    }
}

This is not semantic code.

<?php
class Calculator
{
    public function Add($a, $b)
    {
        return $a + $b;
    }

    public function Substract($a, $b)
    {
        return $a - $b;
    }

    public function Divide($a, $b)
    {
        return $a / $b;
    }

    public function Multiply($a, $b)
    {
        return $a * $b;
    }
}

This is semantic code.

The difference between the two is that the second example class and
method names carry a meaning. When reading the code, you don’t have to
remember what the ‘Add’ method does because it’s clearly indicated
within its name.

In the first example, you have to remember which method name does what.
In the second example, what the method does is its name. It’s a major
difference.

Speaking in cognitive terms. Writing code should be a high cognitive
effort in order for the reading process to be a low cognitive effort.

Don’t forget that code is often read 100x time more that it’s written!

Now let’s apply semantic coding principle to exceptions!

Too much sfException is bad for the health

The use of sfException is a commong thing among all symfony projects’
code I have the chance to read. While it’s harmless to use it from time
to time, I think that using nearly only sfException in your code is like
using $a, $b or $c as unique variable name.

What is sfException?

As the sfException phpDoc says: > sfException is the base class for all
symfony related exceptions and provides an additional method for
printing up a detailed view of an exception.

If you look at the code of
sfException you’ll see that sfException has a bunch of tool to wrap an exception
inside an sfException. That’s why when an exception of any kind is
thrown in symfony, you see a nice html output.

In a symfony application, every thrown exception that bubbles up is
eventually catched in the sfFrontWebController
class. Then this exception is wrapped into an sfException one and is
displayed to the user.

The catching mechanism

 <?php
 try
 {
     // application running…
     […]
 }
 catch (sfException $e)
 {
     $e->printStackTrace();
 }
 catch (Exception $e)
 {
     sfException::createFromException($e)->printStackTrace();
 }


The wrapping mechanism

<?php
static public function createFromException(Exception $e)
{
    $exception = new sfException(sprintf('Wrapped %s: %s', get_class($e), $e->getMessage()));
    $exception->setWrappedException($e);
    self::$lastException = $e;

    return $exception;
}

As you can see, sfException was created mainly to display a nice debug
trace and not to replace ALL exceptions! Don’t worry to throw other
exception php provides, there’s always be a nice debug trace! 😉

PHP provides a lot of different exceptions

PHP provides 2 predefined exceptions known as Exception and
ErrorException.

Exception is the base class from where all other exceptions inherit
from. ErrorException can be used when you want that PHP throws exception
instead of reporting errors. For more information about ErrorException,
you can read the dedicated
documentation
.

The Standard PHP Library (SPL) provides 13 more
exceptions
. These exceptions
are:
BadFunctionCallException,
BadMethodCallException,
DomainException,
InvalidArgumentException,
LengthException,
LogicException,
OutOfBoundsException,
OutOfRangeException,
OverflowException,
RangeException,
RuntimeException,
UnexpectedValueException.

Each of these exception have a name that provide information on what the
problem is which is pretty useful.

Now let’s use those exceptions and see how they improve the global
readability (and scanability) of your code.

Semantic exceptions

Let’s read those two pieces of code.

This one with the uncool sfException everywhere:

<?php
class Container
{
    protected
        $maxItemCount = 2,
        $container = array();

    public function addItem($item)
    {
        if (count($this->container) < $this->maxItemCount)
        {
            $this->container[] = $item;
        }
        else
        {
            throw new sfException('Cryptic long message saying container is full');
        }
    }

    public function sliceItem()
    {
        if (empty($this->container))
        {
            throw new sfException('Cryptic long message saying container is empty');
        }

        array_slice($this->container);
    }
}

And the cool one with semantic exceptions:

<?php 
class Container
{
    protected
        $maxItemCount = 2,
        $container = array();

    public function addItem($item)
    {
        if (count($container) < $this->maxItemCount)
        {
            $container[] = $item;
        }
        else
        {
            throw new OverflowException('Cryptic long message saying container is full');
        }
    }

    public function sliceItem()
    {
        if (empty($container))
        {
            throw new UnderflowException('Cryptic long message saying container is empty');
        }

        array_slice($container);
    }
}

In the second example, you don’t have to read the message to know what
it’s all about. The name is sufficient. Furthermore, you’ll get more
informations while scanning the code with correct exceptions name than
with sfException everywhere.

More significative code = More readable code = More scannable code =
Happy developer = Rainbows in kittens’ eyes.

Keep cool, use vim

Fed up by using Eclipse (So slow) and Netbeans (always crashing), some
folks at Sensio Labs told me to start using Vim. At first, I said: “Just
the name makes me want to puke, but why not.”. A few weeks later, guess
which tool I used to edit my code? Yes, Vim. No, I didn’t even puke!

VIM does not stand for “VIM Is Magic” but it could. It’s lightweight and
usable everywhere. Whether you’re editing code, writing a blogpost in
markdown or configuring an apache vhost over an ssh connection, it’s a
wonderful tool to do the job.

The hard part with vim is the learning. It will take you some time… But it worth it.

The exquise beauty of vim is that it’s nearly entirely customizable. If
you’re not satisfied with keyboards shortcut, change them! Do you want
to have the key F10 do something when you type it, you can! I configured
this key to remove spaces filled lines in my code with a simple regular
expression.

VIM is so customizable and extendable that with installing a few plugins
and tools, you can transform it in a full featured blazing-fast IDE.

The first thing you need to do is to install “exuberant-ctags”. Without
it, vim cannot auto-complete from files you didn’t open or jump to
another method in other files. Once your tags are generated, the
method-hop won’t be as good as eclipse because it’s not contextual, but
it’s pretty acurate and it’s DAMN FAST!

Then I use these plugin to give an “IDE” feel to my vim:

  • NERDTree: A file explorer in your vim? yay!
  • minibufexplorer: Switch between buffers easily!
  • NERDCommenter: (Un)/Comment your code quickly
  • snipMate: I can haz Textmate styles snippets!
  • surround: Tired of navigating through your code to change double
    quote to simple quote? Surround do it with only a few strokes.
  • php-doc: Speed up the phpDoc editing
  • Align: Align your code in a few strokes!
  • matchit: Navigate in control structures or html tags, only with the
    % key.

Also, one of the more important point of using vim: It’s available
anywhere.

But be warned, once you’ll get used to the vim philosophy, it will be
difficult to switch back to an other IDE. 😉

If you’re curious and want to give a try without searching and
installing the plugin by yourself, clone my vim
config
. But you’ll still have to
read the docs 😉