Hello all,
I am wondering if someone could comment on the quality of my code.
I am working on a project and would like to know whether what I am writing is 'good enough'.
The following code is an extract from the app:
<?php
//ajax_handler.php
//Main configuration file which includes all config files (Defines are made here)
require_once('../config/main.php');
// Auto loader to automatically load classes and other files
require_once('../auto_loader.php');
//If debug is defined as true then display errors
if(__DEBUG__) {
error_reporting(E_ALL);
ini_set('display_errors', 1);
}
//Try block for easier error management
try {
//Create a new instance of the core class to access it's methods
$core = new Core;
//Check if controller is sent through both get and post
if( !isset($_GET['controller']) || !isset($_POST['controller']) || empty($_POST['controller']) ) {
throw new Exception(Core::l_static('Invalid parameters received.'));
}
//Check if the post controller is the same as the get controller
if( $_GET['controller'] != $_POST['controller'] ) {
throw new Exception(Core::l_static('Invalid parameters received.'));
} else {
$controller = $_POST['controller'];
}
//Check if file exists, if yes then assign the file path to a variable
if( $file_name = Core::get_file_name(__DIR__ . '/controllers/' . ucwords($controller) . '.php') !== False ) {
//Include the required file
require_once $file_name;
//Format class name and create an instance
$class_name = ucwords($controller) . 'Controller';
$controller = new $class_name;
//Check if the default 'execute' method exists in the class
if( method_exists($controller, 'execute') === False ) {
throw new Exception(Core::l_static('System error. [Execute does not exists]'));
}
//Assign the result of method to variable
$result = $controller->execute($_REQUEST);
//If the method returned false then throw an exception
if( $result === False ) {
throw new Exception(Core::l_static('Operation failed. [Method returned false]'));
}
//If posted via ajax return as JSON otherwise redirect to controller page
if( isset($_GET['ajax']) ) {
echo json_encode($result);
} else {
//Somehow AJAX did not load
header('Location:' . get_class($controller));
}
} else {
throw new Exception(Core::l_static('Invalid parameters received. [Invalid Controller]'));
}
} catch(Exception $e) {
//Catch exceptions and return them to the user
if( isset($_GET['ajax']) ) {
//Return as JSON if AJAX is enabled
echo json_encode(['errors' => $e->getMessage()]);
} else {
//If AJAX is not enabled then return the error encoded using base64
header('Location:' . __HOMEPAGE__ . '?error=' . base64_encode($e->getMessage()));
}
}
This piece of code process AJAX (and ordinary POST requests if the JS scripts fail to load for any reason) POST requests.
I have a 'semi-MVC' structure set up (Classes, Controllers and Views).
Thanks.
<P.S. I am aware of the fact that this post might be a bit vague/useless and I am sorry for this.>