Developing our first plugin, part 2

4th March, 2019 in #Plugins

This article is part of the Our first plugin series

In this example, we’ll build on our first plugin and introduce a couple of new concepts.

Plugins with multiple functions

A single plugin file can encapsulate any number of related functions. To add more than one function we add an extra segment to the tag. For example, our {exp:hello_world} tag could become {exp:hello_world:display}. The 3rd segment should describe the tag’s function.

Adding the new tag to the plugin is as simple as adding a new method to the plugin’s class that corresponds to the tag’s 3rd segment.

public function display() {
    return "Hello, world";
}

Note, that we have no longer use the $return_data variable. When using the display method we can simply return the value that we want to display rather than assigning it to the $return_data variable (the $return_data variable is only used because PHP constructors cannot return a value).

We could add more functions to our plugin by adding new methods to our plugin’s class.

Getting data into the plugin

There are 2 ways to provide the plugin with data.

Parameters

Parameters allow you to pass small bits of information to the plugin and are usually used to configure how the plugin works, eg:

{exp:hello_world:display name="Fred"}

Here’s how we access this data:

public function display() {
    $name = ee()->TMPL->fetch_param('name', 'world');
    return 'Hello, ' . $name . '';
}

The fetch_param method (of EE’s Template class) takes the tag parameter name as the first parameter and a second (optional) default value for when the tag parameter is not set. In this case, if the name= parameter is missing from the template tag the default value of world will be used.

Tag data

Tag data is made available by using tags pairs in a template, eg:

{exp:hello_world:display}Bob{/exp:hello_world:display} 

When a tag pair is used, the contents between the opening and closing tags can be used by the plugin.

public function display() {
    $tagdata = ee()->TMPL->tagdata;
    return 'Hello, ' . $tagdata . '';
}

In this case, we get the data using the ee()->TMPL->tagdata property.

Summary

We’ve quickly seen how to make a plugin with a number of different functions, and we’ve fetched data from the template to use within the plugin.