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 < $count; $i++) {
$filename = $this->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";
}
}
else
{
$this->load_output['error'][] = "PlugCMS has detected the default plugin directory is missing ({$this->plugin_dir}). Please check the installation and try again..";
}
}
@require_once
really makes my blood boil. Please don't use the@
operator of death: if you see a warning/notice/error, FIX IT, don't silence it. \$\endgroup\$@include_once
too as suggested by @tim and @janos \$\endgroup\$@
. If an include produces an error/warning/notice, then you should work out why it does so, and fix the root cause. Supressing the error doesn't fix the problem. Think of it as cleaning your house: you can wipe the dirt under the carpet so you don't see it, but it's still there; or you can get a vacuum cleaner and remove it entirely. The latter is the cleaner option. \$\endgroup\$