J

Flip - Bringing feature toggling to Drupal

06 Mar 2015

When you are working on a large project sometimes you need the ability to gradually roll out a new feature to public facing users. Out of the box, Drupal doesn’t provide too much to assist you with this however one option is to riddle your code with ‘if-something-then-do-something’ checks but what happens if you need to update that condition? You’ve then got to go back through and redo all the conditionals and what happens if you miss one and suddenly your checks no longer match up?

To combat this, many other frameworks and applications implement feature toggles which allow you to implement checks around your code and manage a single source for the conditional. By using feature toggling, you still need to implement your if conditionals, however the checks are all maintained in a single place so this no chance of it getting out of sync with each other.

Now that you know what feature toggling is and how it’s going to benefit your site, you’ll need to go and install flip.

Putting it into action

Once the module is installed, you’ll need to register your toggle with the flip module - you can do this by implementing hook_flip_info within the module which the toggle will be used in.

<?php

function MYMODULE_flip_info() {
  return array(
    'example_toggle' => array(
      'name' => 'Example toggle',
      'description' => 'This is my example description for a toggle.',
      'condition' => 'my_condition_check',
    ),
  );
}

Be sure to check the docs on what each key does!

The main bit here is the condition key. This is the callback you wish to toggle based on - some examples used within these callbacks are: particular user roles, percentage of requests or time of the day. For simplicity sake, the conditional I will be using is that the username is “Jacob”.

<?php

function my_condition_check() {
  return ($user->name == "Jacob") ? TRUE : FALSE;
}

Once you have defined the hook_flip_info and flushed caches, all the implementing toggles should now be visible at admin/config/development/flip

Note: For a toggle to work, it must be marked as enabled in admin/config/development/flip AND the condition callback must return TRUE. This is quiet powerful as it allows you to disable a toggle via the adminsitration UI in the event of something going wrong and you not being able to make a code push to change it.

Now it’s time to test the toggle!

<?php

// Account for both outcomes. Handy for backwards compatibility.
if (flip_enabled('example_toggle')) {
  do_awesome_new_thing();
}
else {
  use_old_functionality();
}

// Just do something new.
if (flip_enabled('example_toggle')) {
  do_awesome_new_thing();
}

To explore this more, be sure to check out the following articles which demonstrate how powerful feature toggling can be.