Learn

Modifiers

Create your own variable modifiers.

You can create and use your own variable modifiers. All of Statamic’s core modifiers use this same setup. The Modifier object has been attached to the existing add-on stack, meaning that they can share data with other add-on aspects as well as use the add-on’s configuration file (if there is one).

Creating a Modifier

Create a file in your add-on containing the object that will hold your modifier’s code. If your add-on is in a folder called flannelize, your modifier file will be mod.flannelize.php. The mod is for modifier. This file goes on the root-level of your add-on’s folder.

Next, within that file we need to create a Modifier object (which extends the Addon object). This class should be Modifier_ followed by the name of your add-on as it exists in its folder name. In this class, create a public index method. This method should accept $value as its first parameter, and an optional $parameters as its second parameter.

For our example:

<?php
class Modifier_flannelize extends Modifier
{
    public function index($value, $parameters=array())
    {

    }
}
?>

The $value being passed in is the value of the variable being modified. If other modifiers were in the chain before it, the value being passed in is where it stands at this point in the chain. This method’s mission is to return the new modified value.

The optional $parameters list is any parameters that were set when the modifier was used. For our example, of the call was {{ my_var|sample:14 }}, the $parameters[0] variable will be set to 14.

Within this method, we can perform any PHP code we want to get the modified value of $value. This includes accessing any information stored in any of the add-on’s data-storing facilities ($this->cache, $this->session, $this->blink, $this->cookies, and $this->flash), using methods defined in the add-on’s Tasks object ($this->tasks), accessing values from the configuration file if it exists ($this->fetchConfig($key)), and even accessing other add-ons via their defined APIs ($this->addon).

To complete our example, let’s say that we want to apply str_rot13 and strrev to any variable that this modifier is applied to. This would look like this:

<?php
class Modifier_flannelize extends Modifier
{
    public function index($value, $parameters=array())
    {
        return strrev(str_rot13($value));
    }
}
?>

We apply each method and return the new value. If there are other modifiers in the chain, this returned value will be passed to those for further modification. Otherwise, this will be the value displayed on the screen.

This article was last updated on September 13th, 2016. Find an error? Please let us know!