Is there a way to put this PHP into an array and simplify it?
The following code loads all .php files found in the specified folder (defined separately). Is there a way to put this into an array to simplify the code?
Only a couple of variables change but essentially the code repeats several times.
// The General Files
$the_general = opendir(FRAMEWORK_GENERAL);
while (($the_general_files = readdir($the_general)) !== false) {
if(strpos($the_general_files,'.php')) {
include_once(FRAMEWORK_GENERAL . $the_general_files);
}
}
closedir($the_general);
// The Plugin Files
$the_plugins = opendir(FRAMEWORK_PLUGINS);
while (($the_plugins_files = readdir($the_plugins)) !== false) {
if(strpos($the_plugins_files,'.php')) {
include_once(FRAMEWO开发者_C百科RK_PLUGINS . $the_plugins_files);
}
}
closedir($the_plugins);
There are several more sections which call different folders.
Any help is greatly appreciated.
Cheers, James
I nicer way to do this would to use glob(). And make it into a function.
function includeAllInDirectory($directory)
{
if (!is_dir($directory)) {
return false;
}
// Make sure to add a trailing slash
$directory = rtrim($directory, '/\\') . '/';
foreach (glob("{$directory}*.php") as $filename) {
require_once($directory . $filename);
}
return true;
}
This is fairly simple. See arrays and foreach.
$dirs = array(FRAMEWORK_GENERAL, FRAMEWORK_PLUGINS, );
foreach ($dirs as $dir) {
$d = opendir($dir);
while (($file = readdir($d)) !== false) {
if(strpos($file,'.php')) {
include_once($dir . $file);
}
}
closedir($d);
}
A better idea might be lazy loading via __autoload or spl_autoload_register, including all the .php files in a directory might seem like a good idea now, but not when your codebase gets bigger.
Your code should be layed out in an easy to understand heirarchy, rather than putting them all in one directory so they can be included easily. Also, if you dont need all of the code in the files in every request you are wasting resources.
Check http://php.net/manual/en/language.oop5.autoload.php for an easy example.
This can be done pretty tightly:
$dirs = array(FRAMEWORK_GENERAL, FRAMEWORK_PLUGINS);
foreach($dirs as $dir) {
if (!is_dir($dir)) { continue; }
foreach (glob("$dir/*.php") as $filename) {
include($filename);
}
}
Put that in a function where $dirs comes in as a param and use freely.
精彩评论