kteus
kteus

Reputation: 41

How to write simple plugin support in PHP?

I'm currently writing a little PHP application for myself for which I'd like to add a simple plugin extensibility.

I did found some ideas on how to do this, but I had the feeling they all were way too complex for my needs.

Let me explain what exactly I need:
My application is supposed to do one simple task, for example: perform a web search.
The user should be able to choose, which plugin is getting used.
For example, you could have a Google, Yahoo, and Bing plugin to choose from.
Each plugin would have a function "performWebSearch" which returns the search results.
Yeah, that's basically it.

I can show you what code I currently use, to make it more clear:

To get a list of existing plugins:

$classes_before = get_declared_classes();
foreach(glob("../plugins/*.plugin.php") as $filename) include $filename;
$classes_after = get_declared_classes();

foreach($classes_after as $class)
{
    if(!in_array($class, $classes_before))
    {
        $plugins_available[] = $class;
    }
}

And this is how a "plugin" currently looks like:

class google
{
    public $name = "Google Search";
    public $version = 1.0;

    public function performWebSearch($query)
    {
        // ...
    }
}

This works, but it feels "dirty" doing it that way.
I'm sure there is a way better method to do this but I have no idea what it could be.

I appreciate any help.
Thanks.

Upvotes: 4

Views: 1111

Answers (2)

Kwebble
Kwebble

Reputation: 2075

For the simple system you describe where you write both application and plugins here's a possible implementation:

Put the plugins in their own folder. This makes all plugins easier to recognize as not part of the base code of the application.

Name the plugin files Search[name].php and the search classes Search[name], where [name] is a search engine like Google.

Assuming $engineName holds the name of the selected engine, include the file with the matching plugin:

include "your_folder/$engineName_search.php";

Create the search object and perform the search:

$searchClass = "Search$engineName";
$engine = new $searchClass();
$result = $engine->performWebSearch($search);

Upvotes: 0

Charlotte Dunois
Charlotte Dunois

Reputation: 4680

Your solution is indeed dirty and shouldn't be used. You could use the __autoload() function to load the necessary plugin. You may still have to scan the plugins directory to look which plugins are available, but you should only load (include) the necessary plugin.

https://www.php.net/manual/en/language.oop5.autoload.php

Upvotes: 2

Related Questions