yarek
yarek

Reputation: 12044

How to use composer's autoload when I already use autoload?

I have a config.php file where I use autoload for all my personal classes

function __autoload($class_name) {
    include __DIR__.'/classes/'.$class_name . '.php';
}

I need now to use a 3rd party class from composer which is located in /vendor/guzzlehttp.

So my code is now:

require('Config.php'); // my config file: this is used in ALL site
require 'vendor/autoload.php'; // the copmoser 
$client = new GuzzleHttp\Client([]); // call to the 3rd party class installed by composer

Which raises a 404 error : php searches GuzzleHttp in /classes

Uncaught Error: Class 'GuzzleHttp\Client' not found

I have no idea on how to solve that: I need to keep my own classes in /classes

I need to autoload them because all the website uses that.

So: how can I use classes installed by composer in my website?

My composer.json content is:

{
    "require": {
        "firebase/php-jwt": "^5.0"
    }
}

Upvotes: 0

Views: 1249

Answers (2)

Sammitch
Sammitch

Reputation: 32232

__autoload() is deprecated and seems to be incompatible with current best practice, spl_autoload_register(), which is what Composer uses.

function myAutoload($class_name) {
    include __DIR__.'/classes/'.$class_name . '.php';
}
spl_autoload_register('myAutoload');

But you should really look at moving your dependencies into that dependency manager that you already have, Composer.

For external libs that are already in Composer, like Guzzle: https://packagist.org/packages/guzzlehttp/guzzle

For internally-developed libs: https://getcomposer.org/doc/04-schema.md#autoload

Edit: on second look there's no reason @Devon's answer wouldn't work.

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35337

Autoloaders can be stacked just fine, but you'll want a check in place to see if the file exists before trying to include it.

However, if you're using Composer already, just let Composer handle the autoloading.

Add a reference to your global namespace being loaded from the classes directory in your composer.json's autoload PSR-4 section:

"autoload": {
    "psr-4": {
        "": "classes"
    }
},

Upvotes: 3

Related Questions