Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 804
DevOverlord Avatar asked Mar 24 '15 06:03

DevOverlord


People also ask

What is PHP spl_autoload_register?

spl_autoload_register() allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a "new Class" is declared.

How to use spl_ autoload function in PHP?

Description ¶ Register a function with the spl provided __autoload queue. If the queue is not yet activated it will be activated. If your code has an existing __autoload() function then this function must be explicitly registered on the __autoload queue.

What does autoload PHP do?

By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error. Any class-like construct may be autoloaded the same way. That includes classes, interfaces, traits, and enumerations.


1 Answers

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.

like image 141
DevOverlord Avatar answered Sep 30 '22 04:09

DevOverlord