I am looking for the cleanest, most elegant way to build OS-safe path strings in PHP 8 and include them in my autoload function, without str_replace() or substr(), if possible.
I have a file structure like this:
NameOfProject
├──(...)
├──src
| ├──Controller
| | └──(...)
| ├──Helper
| | └──(...)
| ├──Model
| | └──(...)
| ├──View
| | └──(...)
└──index.php
Every class in the src folder is namespaced accordingly, for example NameOfProject\src\Controller.
I want to autoload every class, using the spl_autoload_register() function.
This is my code:
<?php
//index.php
spl_autoload_register(function($class)
{
include
dirname(__FILE__, 2)
.'/'
.str_replace('\\', '/', $class)
.'.php';
});
I am wondering if there is a more elegant way to avoid the str_replace(), but without it, the concatenation of the path string doesn't work, because $class always returns the namespace (with backslash) and not the actual path.
I have read that PHP already transforms forward slashes / to DIRECTORY_SEPARATOR within functions, but I think I remember having an issue with using just forward slashes in the past.
If the str_replace() has to be there, maybe using DIRECTORY_SEPARATOR is in order? Like so:
str_replace('\\', DIRECTORY_SEPARATOR, $class)
I have also considered the option to strip the class name from $class, but this, too, requires an "ugly" substr():
$class = substr($class, strrpos($class, "\\") + 1);
If your code structure is very neat, you can just use the default autoload implementation, see notes in this page:
This method will try to load the class
NameOfProject\src\Controller\MyControllerfromnameofproject/src/controller/mycontroller.php.