Search code examples
phpnamespacesrootspl-autoload-register

default spl_autoload_register() namespace behavior with index.php outside root


With modern PHP, calling

spl_autoload_register();

allows you to instantiate new classes without having to specify REQUIRE, INCLUDE nor USE within your php files, as long as they have a namespace, and as long as that namespace follows a folder/file structure such as:

|--models
     |-- utility
|           |___calculator.php
|
|
|--index.php

With such setup, if calculator.php has declared on its top "namespace models\utility", and it contains the class Calculator (a match to the file name calculator.php) you can automatically instantiate it from index.php by calling:

calc = New models\utility\Calculator();

However, if the folder structure is like this:

|--models
     |-- utility
|           |___calculator.php
|
|
|--public
     |--index.php

Now index.php can no longer access calculator through its namespace, as index.php is no longer at the root folder.

It seems that there is no way for public/index.php to reach namespaces above its level. It is just a limitation of PHP. Is there a way perhaps to register a function with spl_autoload_register that would retain its automatic, easy to work with behavior but allowing index.php to instantiate namespaces above its folder level? Or another way to deal with this situation while still never having to USE nor REQUIRE/INCLUDE files?


UPDATE WITH ANSWER

This is a directory agnostic solution that worked for me. I can successfully instantiate new classes merely by calling their namespace, without having to resort on USE, REQUIRE nor INCLUDE even though index.php was moved to the /public folder.

//'/../../../../' points the autoloader.php file back to root directory
$include_path = realpath(dirname(__FILE__) . '/../../../../');         
set_include_path($include_path);
spl_autoload_register();

Solution

  • When the spl_autoload_register() function is called without the $autoload_function argument, the default autoloading function spl_autoload() is used.

    The spl_autoload() function checks all include paths for the file, matching namespaces to folders and class names to files as you have already noted.

    The key for you is to make sure that the folder containing the directory structure with your class files (i.e. the directory that contains models) is on the include path. This is commonly done using the set_include_path() function.