HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpModerate

Pluggin' in Plugins

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
plugginpluginsstackoverflow

Problem

I'm currently working on an in-house project and a part of that project is this pretty standard plugin loader below.

There must be a way to avoid so many ugly looking else statements.

I'm kinda hitting a brick wall with getting better at "writing less to achieve the same thing".

How I can improve the code as I do think it's pretty clean, but I got this aching feeling that I've been missing a lot of "shorthanding" my code?

```
/**
* Load plugins specified by the array $load, containing the leading filenames in the /src/plugins/ folder
All plugins must be proceeded with .plugin.php where the asterisk is the name of the respective plugin
*
* @since 0.1
* @param array $load e.g: array("Users", "Products", "Pages")
* @return void
*/
public function __construct($load) {

$this->plugin_dir = $_SERVER['DOCUMENT_ROOT'] . "/PlugCMS/src/plugins";

require_once($this->plugin_dir . "/Users.default.php"); // Included by default, and is required to gain access to the dashboard
require_once($this->plugin_dir . "/Pages.default.php"); // You can remove this but you will need to remove the pageLoader.php mod_rewrite rule from .htaccess to get control of the front-end back.

if (is_dir($this->plugin_dir)) {
if (is_array($load)) {

$count = count($load);

for ($i=0; $i plugin_dir . "/" . $load[$i] . ".plugin.php";

if (file_exists($filename)) {

if (@require_once($filename)) {
$this->load_output['active'][] = $load[$i];
}
else
{
$this->load_output['failed'][] = $load[$i];
}

}
else
{
$this->load_output['failed'][] = $load[$i];
}
}

}
else
{
$this->load_output['error'][] = "Error: $load must be an array";
}

Solution

I think surely there must be a way to avoid so many ugly looking else statements.

Return early, for example:

if (is_dir($this->plugin_dir)) {
    $this->load_output['error'][] = "PlugCMS has detected the default plugin directory is missing ({$this->plugin_dir}). Please check the installation and try again..";
    return;
}


You can do the same for is_array($load), and already you got rid of two levels of nesting.

You can also combine file_exists($filename) and @require_once($filename) to file_exists($filename) && @require_once($filename) to get rid of another level of nesting.

Code Snippets

if (is_dir($this->plugin_dir)) {
    $this->load_output['error'][] = "PlugCMS has detected the default plugin directory is missing ({$this->plugin_dir}). Please check the installation and try again..";
    return;
}

Context

StackExchange Code Review Q#67684, answer score: 17

Revisions (0)

No revisions yet.