Use Feature Toggles in Magento

Today, Joshua Warren asked an interesting question on Twitter:

I had thought about the topic earlier and if some genereric feature flag module would be worth developing. My conclusion was that it was too trivial in the end and I would just build feature toggles as needed for the respective project.

Feature Toggles: What and Why?

Feature toggles are a way to roll out partially developed features and keep them disabled in production, so it is often mentioned in the context of continuous delivery. They support the “ship early and often” paradigm and decouple code deployment from feature activation.

But feature toggles (or “feature flags”) also can be used to roll out new features gradually, for example only for a certain customer group, based on user location, or for randomly selected users, as with A/B testing.

Magento 1: Example

This is how I have implemented feature flags for a Magento 1 project. I only needed to activate the features per store, so it’s leveraging Magento system configuration for toggling.

Toggle Helper

This helper contains only constants for each feature flag and a isEnabled() method:

class Foo_Bar_Helper_Toggle
{
    const FEATURE_NEW_AWESOME_FEATURE = 'foo_bar/features/new_awesome_feature';
    // a few more ...

    public function isEnabled($feature)
    {
        return Mage::getStoreConfigFlag($feature);
    }
}

Code With Toggleable Features

class Foo_Bar_Model_Something
    protected $toggle;
    public function _construct()
    {
        $this->toggle = Mage::helper('foo_bar/toggle');
    }
    public function thisIsAMethodUsingTheNewFeature()
    {
        if ($this->toggle->isEnabled(Foo_Bar_Helper_Toggle::FEATURE_NEW_AWESOME_FEATURE)) {
            // do the new stuff
        }
    }
}

or if we need to add a new block in layout XML, it can be created outside the hierarchy and conditionally inserted:

<layout>
    <default>
        <block name="new_awesome_block" type="core/template" template="foo_bar/block.html" />
        <reference name="content">
            <action ifconfig="foo_bar/features/new_awesome_feature" method="append">
                <block>new_awesome_block</block>
            </action>
        </reference>
    </default>
</layout>

That’s it?

Yes. As stated above, for my purposes so far it was enough to enable features per store, so using a configuration flag and this very simple API was enough. If I needed to toggle features based on other factors to roll it out gradually, I would probably try to integrate the nice Qandidate Toggle library, but until now, it was not necessary.

Magento 2: Module

James Cowie chimed in with this announcement:

The module is work in progress, but as it’s planned to implement conditions, it might be worth keeping an eye on it!

Are you working with feature toggles? If so, how?