if statement - foreach loop that include php files multiple times - acceptable? -
i have function "processmessage($msg)" processes string based on first few words in (prefixes).
i pull lots of rows database , pass each $msg string through said function...
the caveat here that, function doesn't have "if($prefix=='blah')" conditions, rather includes bunch of php files contains these conditions.
why?
because instead of hard coding bunch of conditions in 1 function, wanted organize each condition through separate php files portability, customization etc (long story here)
so looks (keeping code simple):
main script loads rows database , puts messages in array $msg_r loops through each msg as:
foreach (msg_r $key=>$msg){ processmsg($msg); }
the actual processor function :
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 above prefixes.. instead of hard coding multiple if conditions here, load if else conditions files. require("condition1.php"); require("condition2.php"); require("condition3.php"); //my actual require code in loop loads files found in target directory }
the conditions files php code of if else condition each purpose, eg:
if($prefix1 == 'reboot' , $prefix2 == 'machine') { // }
so it's simple setup seems work during tests, wonder if "normal" or "acceptable" strategy, or if ya'll can suggest different approach?
regards
use array of functions, , have each include file define function , push onto array. main script contain:
$test_array = array(); require ("condition1.php"); require ("condition2.php"); ...
and include files do:
$test_array[] = function($prefix1, $prefix2, $prefix3) { if ($prefix1 == 'reboot' && $prefix2 == 'machine') { // } };
and main function be:
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 $test) { $test($prefix1, $prefix2, $prefix3); } }
Comments
Post a Comment