2

I'm trying to make a loadPlugin(plugin) function that would take and get the php file from the plugin folder and load its variables/functions into the site.

Issue is that as we all know functions are not global which brings up my issue.

As any file could be included I cant make each variable in the file a global as they can be random and infinite and I'd like to make it so any functions in the file can be used anywhere on the page.

Any suggestions on how to do this would be great. Thanks!

this is what i have so far:

function loadPlugin($name,$debug='') {
    if(file_exists("scripts/plugins/".$name)) {
        include("scripts/plugins/".$name);
    } else if(strtolower($debug)=='d') trigger_error($name." does not exists in the plugins folder.", E_USER_ERROR);
}

4 Answers 4

1

Well, I faced a similar problem and decided to go for something reusable and extensible. So, i just trimmed it up for you just to demo Colin's answer. Code can be improved though :)

<?php
/**
* Autoloader
* @Usage: 
*       // set autoload paths
*       Loader::setPaths(
*               array("interface_path"=>dirname(__FILE__). "/core"),
*               array("plugin_path"=>"/var/www/awesome-app/plugins"),
*               array("controller_path"=>dirname(__FILE__). "/controllers")
* );
* 
* 
*   // Now, the magic
*       Loader::registerAutoloads();
*/

class Loader{

protected static $interfacePath = '';
protected static $pluginPath = '';
protected static $controllerPath = '';

/**
 * Set paths to autoload classes
 *
 * @param string $application
 * @param string $library
 * @todo this part can be cleaner/smarter with less code.
 *  Replace "" for with constants as default folders to search
 */
public static function setPaths($autoload_paths= null)
{
    if(is_array($autoload_paths)){
        self::$interfacePath = array_key_exists("interface_path", $autload_paths) ? 
                        $autoload_paths["interface_path"] : "";

        self::$interfacePath = array_key_exists("plugin_path", $autload_paths) ? 
                        $autoload_paths["plugin_path"] : "";

        self::$interfacePath = array_key_exists("controller_path", $autload_paths) ? 
                        $autoload_paths["controller_path"] : "";

    }       
}


/**
 * Registers autoload functions
 *
 */
public static function registerAutoloads() {
    spl_autoload_register('Loader::loadInterface');
    spl_autoload_register('Loader::loadPlugin');
    spl_autoload_register('Loader::loadController');
    if ( function_exists('__autoload') ) {
        spl_autoload_register('__autoload');
    }
}

/**
 * Checks if a given file exists and load it
 *
 * @param string $filename
 * @return bool
 */
protected static function check($filename)
{
    if(file_exists($filename)){
         include_once $filename;
        return true;
    }
    return false;        
}


/**
 * Interface Loader
 *
 * @param string $className
 * @return bool
 */
static function loadInterface($className)
{
    return self::check(
        sprintf('%s/%s_interface.php',self::$interfacePath, low($className))
    );
}


/**
 * Plugin Loader
 *
 * @param string $className
 * @return bool
 */
static function loadPlugin($className)
{
    return self::check(
        sprintf('%s/%s_plugin.php',self::$pluginPath,low($className))
    );
}



/**
 * Controller Loader.
 *
 * @param string $className
 * @return bool
 */
static function loadController($className){
    $fileName = camelCaseToUnderscore($className);
    return self::check(
        sprintf('%s/%s_controller.php',self::$controllerPath,$fileName)
        );
   }


 }

  ?>

It uses PHP's autoload functions, so please make sure you have them. To resolve conflicts, i added a small registry class(sort of key/value store for unique variables and functions) that fixed conflicts. It Also improved performance. Might be an overkill for your kind of work, but it helped me since mine was quite a big project.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of calling the function, you could try making a file called loadPlugin.php, with this code:

if( file_exists("scripts/plugins/".$name)) include("scripts/plugins/".$name));
elseif( strtolower($debug) == "d") trigger_error("....");

Then, to load a plugin:

$name = "pluginName"; include("loadPlugin.php");

You can include an individual file as many times as you like, just as long as they don't try to redefine functions. So this basically works like a function called in the global scope.

1 Comment

Thats basically what I'm doing now. I was just trying to make it easier to call them and more user friendly for people that also edit my code. I could make name an array and then loop through it only calling loadPlugin() once for each, kind of like what you're saying here.
1

Loading a file that has functionality in it seems wonky. Why don't you create classes and take an object oriented approach?

You can load objects that can be reused throughout your code. You can even implement an interface which would guarantee the existence of certain methods and properties across all of your plugins regardless of who develops them.

As far as "Global" is concerned I can think of few different paths you could go down in regards to persistence that revolve around using session variables to store information for populating the objects each time you load a new page. Or even going as far as storing the objects themselves into session (this is not a best practice but still possible).

2 Comments

Would it just be best to always load all my functions instead of ones that pertain to the page? Do unused functions slow down page loads and such? I mean I don't see downloading a file with 10-15 larger functions to be that bad but I was thinking it would be better to stick to only what I needed per page.
The PHP code is not sent to the client. Its rendered on the server.
0

Create global array for example $pluginVars and inside plugin file store all variables You would like to use outside in this array.

1 Comment

Say its not a variable but a function, can you make that function global? I'm trying to get more into using functions as I've really never used them before as they aggravated me with things like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.