Hi I’ve got the following url http://mywebsite/group/viewGroup/3 then with my router I can analize the url with a router function to get the controller (group), the action (viewGroup) and the parameter (group id 3)
In my controller i’ve got some switch cases where i first detect the action and then detect different ajax calls in this way:
switch ($action) {
case 'viewGroup':
if(isset($_POST['ajax_action']) && !empty($_POST['ajax_action'])) {
$ajax_action = trim(filter_var($_POST['ajax_action'], FILTER_SANITIZE_STRING));
switch($ajax_action) {
case 'km-list-groups':
try{
// Check if the model file exist
if(file_exists(KM_MODEL_PATH.KM_DS.'km-list-groups.php')){
// Load the model file
require_once(KM_MODEL_PATH.KM_DS.'km-list-groups.php');
exit;
}else{
if(IS_AJAX) {
echo km_notice('Operation failed!', "Error in showing group list.", KM_ERROR_CODE, 'error');
exit;
}
}
}catch (Exception $e){
if(IS_AJAX) {
echo km_notice('Operation failed!', $e->getMessage(), $e->getCode(), 'error');
exit;
}
}
break;
}
}
break;
}
Now the problem is thati’ve got several ajax call to this controller and therefore I’ve ended up with a massive number of switch.
My solution would be to create a model file for each ajax action and name this file the same the ajax action and therefore the code would be:
if(isset($_POST['ajax_action']) && !empty($_POST['ajax_action'])) {
// Save ajax action into a variable
$ajax_action = trim(filter_var($_POST['ajax_action'], FILTER_SANITIZE_STRING));
try{
// Check if the model file exist
if (file_exists(KM_MODEL_PATH.KM_DS.$ajax_action.'.php')) {
//Load the model to create a new ticket
require_once(KM_MODEL_PATH.KM_DS.$ajax_action.'.php');
exit;
}else{
if(IS_AJAX) {
echo km_notice('Operation error!', "There was an error.", KM_ERROR_CODE, 'error');
exit;
}
}
}catch (Exception $e){
if(IS_AJAX) {
echo km_notice('Operation error!', $e->getMessage(), $e->getCode(), 'error');
exit;
}
}
}
I’m not using a framework or classes at the moment becuse I’m still learnng basic php. The qestion is do you think this can be a good approach? Do you have any other ideas on how to solve this problem?
Many thanks for your support