I'm working on a project where the admin panel is just a shell that do some actions depending on what string you input. By shell i mean an input box where you type for example
delete user 1
and the user with id 1 is deleted. I have planned this for about 4 months and i have written all the commands that the app could manage. I have some problem to make this system. I was thinking about this solution:
$c = explo开发者_如何学Cde(' ', $input);
if ($c[0] == 'delete' and $c[1] == 'user' and count($c) === 3)
{
$c[2] = $id;
delete_user_by_id($id);
}
But i think it is not that well designed and i'm sure that it could be improved. I noticed that exists regular expression and that they could be better than this but i can't really figure out how to use them in the previous example. Any idea?
{Notice that a part of the string is variable (delete user VARIABLE)}
Instead of a bunch of if statements, you should create a class for each command, which takes the information as an argument and does something. You just need to load the class when it's called.
$command = 'delete user 1';
$parsed = explode($command, ' ', 2);
load_class($parsed[0]); // hypothetical loader
if (class_exists($parsed[0])) {
$class = new $parsed[0]();
$class->execute($parsed[1]);
} else {
die('Sorry, invalid command');
}
I think exploding on spaces is cleaner than using a regex.
You might be able to clean up the code a bit with a switch statement, and trimming the input before you explode it:
$c explode(' ', trim($input));
switch(strtolower($c)) {
case 'delete' :
delete_user_by_id($c[2]);
break;
case 'update' :
update_user_by_id($c[2]);
break;
...
default :
echo 'Invalid command: '.$c;
}
精彩评论