21..02.2025

In stock

Category:
index.php
<?php

// Enable error reporting for debugging (Disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Define the path to bootstrap.php
$bootstrapPath = __DIR__ . '/../app/bootstrap.php';

// Check if bootstrap.php exists before requiring it
if (!file_exists($bootstrapPath)) {
    die("Fatal Error: bootstrap.php not found at $bootstrapPath");
}

// Step 1: Require the bootstrap.php file to initialize the application environment
require $bootstrapPath;

// Step 2: Parse the URL to get routing components (folder, controller, method, params)
$urlComponents = parseUrl($_GET['url'] ?? '');

// Step 3: Initialize the Router with parsed URL components
$router = new App\Core\Router($urlComponents);

// Step 4: Call the route method to process the request and route it to the appropriate controller and method
$router->route();

bootstrap.php
<?php

try {
    
    // Load ErrorHandler first
    $errorHandlerPath = __DIR__ . '/core/ErrorHandler.php';
    if (!file_exists($errorHandlerPath)) {
        throw new Exception("🚨 Fatal Error: ErrorHandler.php not found at " . $errorHandlerPath);
    }

    require_once $errorHandlerPath;

    $errorHandler = new \Core\ErrorHandler();


   // Load class file loader
    $classFileLoaderPath = __DIR__ . '/core/ClassLoader.php';
    if (!file_exists($classFileLoaderPath)) {
        throw new Exception("🚨 Fatal Error: ClassFileLoader.php not found at " . $classFileLoaderPath);
    }
    require_once $classFileLoaderPath;


    // Load config file loader (Last)
    $configFileLoaderPath = __DIR__ . '/config/config_file_loader.php';
    if (!file_exists($configFileLoaderPath)) {
        throw new Exception("🚨 Fatal Error: config_file_loader.php not found at " . $configFileLoaderPath);
    }

    require_once $configFileLoaderPath;


} catch (Throwable $e) {
    die(<<<ERROR
        <strong>⚠ Critical Error:</strong> Failed to load a required file.<br>
        <strong>📝 Reason:</strong> {$e->getMessage()}<br>
        <strong>📌 File:</strong> {$e->getFile()}<br>
        <strong>📍 Line:</strong> {$e->getLine()}
    ERROR);
}

ErrorHandler.php
<?php
namespace Core; // Define the namespace 'Core' to organize the class and avoid conflicts.

class ErrorHandler
{
    public function __construct()
    {
        // Register the custom error handler function for handling standard PHP errors.
        set_error_handler([$this, 'customErrorHandler']);

        // Register the custom exception handler function for handling uncaught exceptions.
        set_exception_handler([$this, 'customExceptionHandler']);
    }

    /**
     * This method is triggered when a PHP error occurs.
     * 
     * int $severity - The error severity level (E_WARNING, E_NOTICE, etc.).
     * string $message - The error message.
     * string $file - The file where the error occurred.
     * int $line - The line number where the error occurred.
     */
    public function customErrorHandler($severity, $message, $file, $line)
    {
        // Ignore errors that are suppressed using the '@' operator.
        if (!(error_reporting() & $severity)) {
            return;
        }

        // Display the error details in a readable format.
        echo "<strong>Error:</strong> $message <br>";
        echo "<strong>File:</strong> $file <br>";
        echo "<strong>Line:</strong> $line <br>";
        echo "<strong>Severity:</strong> $severity <br>";
    }

    /**
     * This method is triggered when an uncaught exception is thrown.
     * 
     * \Throwable $exception - The exception object.
     */
    public function customExceptionHandler($exception)
    {
        // Display the exception details in a readable format.
        echo "<strong>Exception:</strong> " . $exception->getMessage() . "<br>";
        echo "<strong>File:</strong> " . $exception->getFile() . "<br>";
        echo "<strong>Line:</strong> " . $exception->getLine() . "<br>";
    }
}

<?php
//config-app.php
//Application Configuration
return [
    'APP_NAME' => 'My MVC Project',
    'APP_ENV' => 'development',
    'DEBUG_MODE' => true,
    'DEFAULT_TIMEZONE' => 'Asia/Kolkata'
];

<?php
//config-assets.php
return [
'BASE_URL' => 'http://localhost/mvcore/public',
'CSS_PATH' => '/assets/css/',
'JS_PATH' => '/assets/js/',
'IMG_PATH' => '/assets/images/'
];

<?php
//config-css-links.php
//Stores CSS files to include in the project dynamically.
$cssFiles = [
    CSS_PATH . 'style.css',
    CSS_PATH . 'responsive.css'
];
<?php

//config-db.php
// Database connection details
//Database Configuration
return [
    'DB_TYPE' => 'mysql',
    'DB_HOST' => 'localhost',
    'DB_NAME' => 'mvc_db',
    'DB_USER' => 'root',
    'DB_PASS' => ''
];

<?php
//config-directory-settings.php
//Directory Structure & Path Configuration
// Define DIRECTORY_SEPARATOR shortcut
if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

// Define ROOT_PATH (Project Root Directory)
define('ROOT_PATH', realpath(__DIR__ . DS . '..' . DS . '..') . DS);

// Define BASE_PATH (App Directory)
define('BASE_PATH', realpath(__DIR__ . DS . '..') . DS);
?>

<?php

//config_file_loader.php
use App\Core\ConfigManager;

// Calling the static 'loadConfig' method of the 'ConfigManager' class
// This will load the configuration file 'config-app.php' from the current directory
ConfigManager::loadConfig(__DIR__ . '/config-app.php');
ConfigManager::loadConfig(__DIR__ . '/config-db.php');
ConfigManager::loadConfig(__DIR__ . '/config-assets.php');


core/ClassLoader.php
<?php
namespace App\Core;

// Load individual configuration files
require_once __DIR__ . '/../config/config-app.php';   // 🔹 Load app-specific configuration
require_once __DIR__ . '/../config/config-db.php';    // 🔹 Load database-specific configuration
require_once __DIR__ . '/../config/config-assets.php'; // 🔹 Load assets configuration

class ClassLoader {
    public static function load($class) {
        // Modify the path to reflect the actual file location within the 'app' directory structure
        $file = __DIR__ . '/../' . str_replace('\\', '/', $class) . '.php'; // 🔹 Adjusted the path based on directory structure

        // Debugging information based on ENABLE_DEBUG setting
        if (defined('ENABLE_DEBUG') && ENABLE_DEBUG) { // 🔹 Check if ENABLE_DEBUG is defined
            echo "Trying to load: $class <br>";
            echo "Looking for file: $file <br>";
        }

        // Check if the class file exists
        if (file_exists($file)) {
            if (defined('ENABLE_DEBUG') && ENABLE_DEBUG) {
                echo "✅ Found and loading: $file <br>";
            }
            require_once $file;  // Include the file
        } else {
            if (defined('ENABLE_DEBUG') && ENABLE_DEBUG) {
                echo "❌ File not found: $file <br>";
            }
        }
    }
}

// Register autoloader
spl_autoload_register(['App\Core\ClassLoader', 'load']);


core/ConfigManager.php
<?php
namespace Core;

class ConfigManager {
    // Private static property to hold all configuration variables
    private static $config = [];

    // Method to load configuration files
    public static function loadConfig($filePath) {
        if (file_exists($filePath)) {
            require_once $filePath;
            self::$config = array_merge(self::$config, $config); // Merge the configuration into the static $config array
        } else {
            throw new \Exception("Configuration file not found: " . $filePath);
        }
    }

    // Method to retrieve a configuration value by its key
    public static function get($key) {
        return self::$config[$key] ?? null;  // Return the value or null if the key doesn't exist
    }
}

core/ErrorHandler.php
<?php
namespace Core; // Define the namespace 'Core' to organize the class and avoid conflicts.

class ErrorHandler
{
    public function __construct()
    {
        // Register the custom error handler function for handling standard PHP errors.
        set_error_handler([$this, 'customErrorHandler']);

        // Register the custom exception handler function for handling uncaught exceptions.
        set_exception_handler([$this, 'customExceptionHandler']);
    }

    /**
     * This method is triggered when a PHP error occurs.
     * 
     * int $severity - The error severity level (E_WARNING, E_NOTICE, etc.).
     * string $message - The error message.
     * string $file - The file where the error occurred.
     * int $line - The line number where the error occurred.
     */
    public function customErrorHandler($severity, $message, $file, $line)
    {
        // Ignore errors that are suppressed using the '@' operator.
        if (!(error_reporting() & $severity)) {
            return;
        }

        // Display the error details in a readable format.
        echo "<strong>Error:</strong> $message <br>";
        echo "<strong>File:</strong> $file <br>";
        echo "<strong>Line:</strong> $line <br>";
        echo "<strong>Severity:</strong> $severity <br>";
    }

    /**
     * This method is triggered when an uncaught exception is thrown.
     * 
     * \Throwable $exception - The exception object.
     */
    public function customExceptionHandler($exception)
    {
        // Display the exception details in a readable format.
        echo "<strong>Exception:</strong> " . $exception->getMessage() . "<br>";
        echo "<strong>File:</strong> " . $exception->getFile() . "<br>";
        echo "<strong>Line:</strong> " . $exception->getLine() . "<br>";
    }
}

core/Router.php
<?php
namespace App\Core;

use Exception;

class Router
{
    // Declare properties to store the folder, controller, method, and parameters
    protected string $folder;
    protected string $controller;
    protected string $method;
    protected array $params;

    /**
     * Router constructor that takes URL components as input.
     * The components will be used to set the folder, controller, method, and params.
     */
    public function __construct(array $urlComponents)
    {
        // Call the method to set the URL components (folder, controller, method, params)
        $this->setURLComponents($urlComponents);
    }

    /**
     * Get the folder name (e.g., 'user' or 'admin') from the parsed URL.
     */
    public function getFolder(): string
    {
        return $this->folder;
    }

    /**
     * Get the controller name (e.g., 'HomeController').
     */
    public function getController(): string
    {
        return $this->controller;
    }

    /**
     * Get the method name (e.g., 'index').
     */
    public function getMethod(): string
    {
        return $this->method;
    }

    /**
     * Get the parameters (additional parts of the URL after controller and method).
     */
    public function getParams(): array
    {
        return $this->params;
    }

    /**
     * This method is responsible for parsing the URL components and setting
     * the folder, controller, method, and params based on the URL structure.
     * It checks for missing values and assigns defaults if necessary.
     */
    private function setURLComponents(array $urlComponents): void
    {
        // Default to 'user' folder if the folder is not specified in the URL
        $this->folder = $urlComponents[0] ?? 'user';

        // Default to 'HomeController' if no controller is specified in the URL
        // The controller name will be converted to title case and appended with 'Controller'
        $this->controller = ucfirst($urlComponents[1] ?? 'home') . 'Controller';

        // Default to 'index' method if not specified in the URL
        $this->method = $urlComponents[2] ?? 'index';

        // Parameters will contain any additional parts in the URL after the controller and method
        $this->params = $urlComponents[3] ?? [];

        // Apply any special routing rules based on the folder (e.g., 'admin')
        $this->applyFolderRouteRules();
    }

    /**
     * This method applies specific routing rules based on the folder.
     * For example, if the folder is 'admin', we can specify certain default controllers or methods.
     */
    private function applyFolderRouteRules(): void
    {
        // If the folder is 'admin', modify the controller or method if necessary
        if ($this->folder === 'admin') {
            // Set a default controller for the 'admin' folder if none is provided
            $this->controller = $this->controller ?: 'DashboardController';
        }
    }

    /**
     * This method will dynamically load the specified controller and method
     * based on the parsed URL, and will call the method with any provided parameters.
     * If the controller or method does not exist, an exception will be thrown.
     */
    public function route()
    {
        try {
            // Dynamically create the full class name for the controller
            $controllerClass = "App\\Controllers\\" . ucfirst($this->folder) . "\\" . $this->controller;

            // Set the path to the controller file based on the folder and controller name
            $controllerPath = __DIR__ . "/../../controllers/" . $this->folder . "/" . $this->controller . ".php";

            // Check if the controller file exists
            if (!file_exists($controllerPath)) {
                throw new Exception("Controller file '{$this->controller}' not found.");
            }

            // Require the controller file to make the class available
            require_once $controllerPath;

            // Create an instance of the controller class
            if (!class_exists($controllerClass)) {
                throw new Exception("Controller class '{$controllerClass}' not found.");
            }

            $controllerInstance = new $controllerClass();

            // Check if the method exists in the controller class
            if (!method_exists($controllerInstance, $this->method)) {
                throw new Exception("Method '{$this->method}' not found in controller '{$this->controller}'.");
            }

            // Call the method and pass any parameters to it
            call_user_func_array([$controllerInstance, $this->method], $this->params);

        } catch (Exception $e) {
            // Catch any exceptions thrown and handle them (e.g., logging, displaying an error message)
            echo "Error: " . $e->getMessage(); // Display error message (can be customized)
            // Optionally log the error details to a file or monitoring system
            // file_put_contents('error_log.txt', $e->getMessage(), FILE_APPEND);
        }
    }
}

core/View.php
<?php
namespace App\Core;

class View
{
    // Render a view with the provided data
    public function render(string $viewName, array $data = [])
    {
        // Check if the view file exists
        $viewPath = __DIR__ . "/../../views/{$viewName}.php";
        
        if (file_exists($viewPath)) {
            // Extract data to variables
            extract($data);

            // Include the view file
            require_once $viewPath;
        } else {
            // Throw an exception if the view file doesn't exist
            throw new \Exception("View file {$viewName} not found.");
        }
    }
}

See It Styled On Instagram

    No access token

Main Menu