Creating Action Controller in PHP
We could handle actions in PHP like this…
$actions = $_GET['action'];
switch( $actions ) {
case ‘hello’:
say_hello();
break;
case ‘bonjour’:
say_bonjour();
break;
default:
echo ‘Unknown action ‘.$actions;
}
…
?>
But this way is hard to extend and hard to maintain. How about adding say_konichiwa() action? We need to add a function and need to add a case in switch statement. For database management system, we need at least 6 actions. Show List View, Add New, Show, Edit, Update and Delete. If we put all those actions to one page like about example, it will be ugly and hard to read. And, we definitely will need to add another action.
We could make Ruby on Rails style Action Controller in easy way. First we need to create .htaccess for RESTful url.
.htaccess
RewriteRule ^action/([a-z0-9\-\_]*)$ index.php?do=$1 [NC]
RewriteRule ^action/([a-z0-9\-\_]*)/$ index.php?do=$1 [NC]
Then, we need to create three scripts. index.php, actions.php and action_controller.php.
index.php
<html>
<head><title>Index</title></head>
<body><?php actions(); ?></body>
</html>
actions.php
include(‘action_controller.php’);
function say_hello(){
echo ‘Hello World!’;
}
function say_bonjour(){
echo ‘BONJOUR !!!’;
}
?>
action_controller.php (the trick)
function actions(){
$action = $_GET['do'];
if($action == ”){
if(function_exists(‘index’)){
index();
} else {
echo ‘There is no index action !’;
}
} else {
if(function_exists($action)){
//calling function same name with $action
$action();
} else {
echo ‘Unknown Action ‘.$action;
}
}
}
?>
That all…
Now, we can access our say_hello actions with…
If we want to add say_konichiwa action, we can simply put say_konichiwa function to actions.php and we can call our action from browser with ( http://domain/project-dir/action/say_konichiwa ). That is easy to maintain, easy to extend and nice (i think :D).
Have a nice day…
Comments(8)