1

In my PHP project all of the class files are contained in a folder called 'classes'. There is one file per class and as more and more functionality is added to the application the classes folder is growing larger and less organized. Right now this code, in an initialization file, autoloads classes for the pages in the app:

spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';

});

If subfolders were to be added to the existing 'classes' folder and the class files organized within these subfolders, is there a way to modify the the autoload code so it still works?

For example - assume the subfolders within the classes folder looks like this:

  • DB
  • login
  • cart
  • catalog
knot22
  • 2,648
  • 5
  • 31
  • 51
  • possible duplicate of [Autoload classes from different folders](http://stackoverflow.com/questions/5280347/autoload-classes-from-different-folders) – DanMan Feb 01 '14 at 14:45

6 Answers6

3

I recoomend that you look at PSR standards at : http://www.php-fig.org

Also this tutorial will help you build and understand one for yourself. http://www.sitepoint.com/autoloading-and-the-psr-0-standard/

Snippet that takes all subfolder :

function __autoload($className) {
    $extensions = array(".php", ".class.php", ".inc");
    $paths = explode(PATH_SEPARATOR, get_include_path());
    $className = str_replace("_" , DIRECTORY_SEPARATOR, $className);
    foreach ($paths as $path) {
        $filename = $path . DIRECTORY_SEPARATOR . $className;
        foreach ($extensions as $ext) {
            if (is_readable($filename . $ext)) {
                require_once $filename . $ext;
                break;
           }
       }    
    }
}
1

My solution

function load($class, $paste){
    $dir = DOCROOT . "\\" . $paste;

    foreach ( scandir( $dir ) as $file ) {
        if ( substr( $file, 0, 2 ) !== '._' && preg_match( "/.php$/i" , $file ) ){
            require $dir . "\\" . $file;
        }else{
            if($file != '.' && $file != '..'){
                load($class, $paste . "\\" . $file);
            }
        }
    }
}

function autoloadsystem($class){
    load($class, 'core');
    load($class, 'libs');
}

spl_autoload_register("autoloadsystem");
0

Root
|-..
|-src //class Directory
|--src/database
|--src/Database.php // Database Class
|--src/login
|--src/Login.php // Login Class
|-app //Application Directory
|--app/index.php
|-index.php
-----------------------------------
Code Of index.php in app folder to Autoload All the Classes from The src folder.

spl_autoload_register(function($class){
$BaseDIR='../src';
$listDir=scandir(realpath($BaseDIR));
if (isset($listDir) && !empty($listDir)) 
{
    foreach ($listDir as $listDirkey => $subDir) 
    {
        $file = $BaseDIR.DIRECTORY_SEPARATOR.$subDir.DIRECTORY_SEPARATOR.$class.'.php';
        if (file_exists($file)) 
        {
            require $file;
        }
    }
}});

Code Of index.php in root folder to Autoload All the Classes from The src folder.
change the variable $BaseDIR,

$BaseDIR='src';
Simple Test
  • 157
  • 1
  • 4
0

autoload.php

<?php
    function __autoload ($className) {
        $extensions = array(".php");
        $folders = array('', 'model');

        foreach ($folders as $folder) {
            foreach ($extensions as $extension) {
                if($folder == ''){
                    $path = $folder . $className . $extension;
                }else{
                    $path = $folder . DIRECTORY_SEPARATOR . $className . $extension;
                }

                if (is_readable($path)) {
                    include_once($path);
                }
            }
        }
    }
?>

index.php

include('autoload.php');
0

Here is the one I'm using

spl_autoload_register(function ($class_name) {
    //Get all sub directories
    $directories = glob( __DIR__ . '/api/v4/core/*' , GLOB_ONLYDIR);

    //Find the class in each directory and then stop
    foreach ($directories as $directory) {
        $filename = $directory . '/' . $class_name . '.php';
        if (is_readable($filename)) {
            require_once $filename;
            break;
        }   
    }
});
Amitoj
  • 171
  • 2
  • 15
0

Load files from "inc" subfolder using "glob"

/**
 * File autoloader
 */
function load_file( $file_name ) {
  /**
   * The folder to where we start looking for files
   */
  $base_folder = __DIR__ . DIRECTORY_SEPARATOR ."inc". DIRECTORY_SEPARATOR . "*";

  /**
   * Get all sub directories from the base folder
   */
  $directories = glob( $base_folder, GLOB_ONLYDIR );

  /**
   * look for the specific file
   */
  foreach ( $directories as $key => $directory ) {
    $file = $directory . DIRECTORY_SEPARATOR . $file_name . ".php";

    /**
     * Replace _ by \ or / may differ from OS
     */
    $file = str_replace( '_', DIRECTORY_SEPARATOR, $file );

    /**
     * Check for file if its readable
     */
    if ( is_readable( $file ) ) {
      require_once $file;
      break;
    }   
  }
}

/**
 * Autoload file using PHP spl_autoload_register
 * @param $callbak function
 */
spl_autoload_register( 'load_file' );
MrFunc
  • 1
  • 1