[英]foreach loop that include php files multiple times - acceptable?
我有此函数“ processMessage($ msg)”,该函数根据字符串中的前几个字(前缀)来处理字符串。
我从数据库中拉出许多行,并通过上述函数传递每个$ msg字符串...
需要注意的是,该函数不具有“ if($ prefix =='blah')”条件,而是包括一堆包含这些条件的php文件。
为什么?
因为我不想在一个函数中对一组条件进行硬编码,而是希望通过单独的php文件来组织每个条件,以实现可移植性,自定义性等(这里有很长的故事)
所以基本上看起来像这样(保持代码简单):
主脚本从数据库加载行并将消息放入$ msg_r数组中,然后循环遍历每个msg,如下所示:
foreach (msg_r as $key=>$msg){
processMsg($msg);
}
实际的处理器功能:
function processMsg($msg){
$msg_r = explode(" ",$msg); // break apart message based on spaces .. eg. "reboot machine 30"
//prepare prefixes
$prefix1 = $msg_r[0];// reboot
$prefix2 = $msg_r[1];// machine
$prefix3 = $msg_r[3];// 30
//process the above prefixes.. but instead of hard coding multiple if conditions here, load if else conditions from files.
require("condition1.php");
require("condition2.php");
require("condition3.php");
//my actual require code is in a loop that loads all files found in a target directory
}
条件文件基本上只是用于ifif条件的php代码,例如:
if($prefix1 == 'reboot' and $prefix2 == 'machine') {
// do something
}
因此,这是一个简单的设置,似乎可以在我的测试过程中使用,但是我想知道这是“正常”策略还是“可接受”策略,或者您是否可以建议其他方法?
关于所有
使用函数数组,并让每个包含文件定义一个函数并将其推入数组。 因此,主脚本将包含:
$test_array = array();
require ("condition1.php");
require ("condition2.php");
...
包含文件将执行以下操作:
$test_array[] = function($prefix1, $prefix2, $prefix3) {
if ($prefix1 == 'reboot' && $prefix2 == 'machine') {
// do something
}
};
您的主要功能将是:
function processMsg($msg){
global $test_array;
$msg_r = explode(" ",$msg); // break apart message based on spaces .. eg. "reboot machine 30"
//prepare prefixes
$prefix1 = $msg_r[0];// reboot
$prefix2 = $msg_r[1];// machine
$prefix3 = $msg_r[3];// 30
foreach ($test_array as $test) {
$test($prefix1, $prefix2, $prefix3);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.