PHP Autoloading and Extraction



This content originally appeared on DEV Community and was authored by Ghulam Mujtaba

Today, I learned how PHP autoloading works, and it allows classes and files to be loaded automatically. I also learned how to perform extraction using a function to retrieve values.
Let’s start the topic

What is Autoloading?

Autoloading is a way to load classes and files automatically without using include or require statements.

What is Extraction?

Extraction is the process of moving reusable code into separate files and classes to keep your code organized.

Implementation Steps

Step 1:Set the Base Path

Define a constant called BASE_PATH that points to the root directory of your project:

define('BASE_PATH', __DIR__ .'/../');
var_dump(BASE_PATH); // Check if the constant is working

If the statement is working properly then move next to execute remaining code.

Step 2:Create an Autoloader

Register an autoloader function that loads classes and files from a specific directory:

spl_autoload_register(function ($class) {
    require base_path($class . '.php');
});

Helper Functions

Add helper functions in function.php file to locate the path that leads to the root of project and to view files.

  • base_path(): Declare a path:
function base_path($path) {
    return BASE_PATH . $path;
}
  • view(): View files in the view directory:
function view($path, $attributes = []) {
    extract($attributes);
    require path('views/'  . '.php');
}
  • When you run&debug to check the working of project, it shows error that you need to include files in code for proper working as:
<?php require base_path('views/partials/head.php') ?> 
<?php require base_path('views/partials/nav.php') ?> 
<?php require base_path('views/partials/banner.php') ?> 

Same for other files that are causing the errors.

Step 3: Create a Core Directory

Create a new directory core in demo that is used to store the core part of project at common point.

Step 4: Select and Paste Reusable Code

Select all important files like “database.php,validator.php, functions.php,router.php, Response.php” and paste all these files in coredirectory. After making these changes when we refresh the output page it shows an error as the path of these files are changed.
To resolve the error caused by the changed file path is very easy go to the index.php file in public directory and add Core/ in autoloader statements.

spl_autoload_register(function ($class) {
    require base_path("Core/{$class}.php");
});

After adding this, when you run the project, the autoloader automatically loads the classes and files, allowing the project to work properly and display the desired output on the screen.
I hope that you have clearly understood this.


This content originally appeared on DEV Community and was authored by Ghulam Mujtaba