Developing our first plugin
4th March, 2019 in #Plugins
This article is part of the Our first plugin series
In this article, we’ll create a simple plugin that displays some text in a template. We can then build on these basic concepts to make a more complex plugin in part 2.
Giving the plugin a name
The first decision when creating a plugin is to give it a name. We’ll call our’s “Hello World”. From this we can generate a short name - this must be lowercase alphanumeric text with underscores replacing spaces (often called Snake case). So “Hello World” becomes “hello_world”.
This will define:
- the template tag (eg,
{exp:hello_world}
) - the plugin’s folder name (eg,
hello_world
) - the name of the plugin file (eg,
pi.hello_world.php
)
Creating the plugin’s file structure
From EE 3 onwards, all plugins also need to be in their own folder containing an addon.setup.php file and the plugin file itself and must be installed from the Add-ons section.
First let’s create a folder for the plugin: hello_world
. In that folder we create the addon.setup.php file:
<?php
return array(
'name' => 'Hello World',
'description' => 'My first plugin',
'author' => 'EE Recipes',
'author_url' => 'https://ee-recipes.com/',
'version' => '1.0.0',
'namespace' => 'EeRecipes\HelloWorld',
);
Most of these settings are obvious, except perhaps the namespace
. This is a unique value (to your add-on) that EE uses to prevent any of your code from getting confused with other add-ons. Typically, this will be a combination of your name or company and the add-on name. There should be no spaces and words are capitalised. (More on namespaces.)
We can then create an empty, main plugin file, pi.hello_world.php
:
<?php
class Hello_world {
public function __construct()
{
}
}
// End of file pi.hello_world.php
Displaying some text
The plugin outputs the template text by returning the value from the class. To return a value from the constructor method, we need to add a new property:
public $return_data;
The constructor then sets the $return_data
property to the text we want to display.
This gives a final pi.hello_world.php
file of:
<?php
class Hello_world {
public $return_data;
public function __construct()
{
$this->return_data = 'Hello, world';
}
}
// End of file pi.hello_world.php
And we’re done!
Now, if we install the add-on and include the tag {exp:hello_world}
in a template, it will display “Hello, world” in its place
This is a very simple plugin but it shows how easy it is to create an add-on. We’ll build on the basic ideas from this introduction to create more complex plugins.