Search code examples
phpcomposer-phpautoloadautoloaderspl-autoload-register

Can php spl_autoload_register & composer autoloader work together?


After a little bit of research and have been unable to locate a solution to my problem. I am utilizing an API that is namespaces that I downloaded via composer. The API has it dependences that I allow composer to manage and autoload for me. Separate from this I have about 10 classes that I have autoloaded with utilizing php's spl_autoload_register. Recently, I started mixing the classes to finish up part a project and the whole thing has gone to crap. My custom classes cannot use the composer classes and visa versa. Is there a method I can use to autoload classes that are in two separate folders and that are loaded with two separate outloader.

Here is the code that I currently use. The vender/autoload.php is no different then your typical composer autoloader. Thanks for any assistance.

require 'vendor/autoload.php';
require 'functions/general.php';
require 'include/mailgun.php';

function my_autoloader($class) {
    require 'classes/' . $class . '.php';
}
spl_autoload_register('my_autoloader');

Solution

  • After further research due to ideas that the both @Etki and @Sarah Wilson gave me I came up with the following solution. Thank You both for your input.

    require 'vendor/autoload.php';
    require 'functions/general.php';
    require 'include/mailgun.php';
    
    
    function autoLoader ($class) {
      if (file_exists(__DIR__.'/classes/'.$class.'.php')) {
        require __DIR__.'/classes/'.$class.'.php';
      }
    }
    spl_autoload_register('autoLoader');
    

    Hint: I added the __DIR__ to the beginning of the file paths inside the autoLoader function.