Avishay28
Avishay28

Reputation: 2456

"Class not found" when trying to use composer auto load for a wordpress plugin

I'm writing a plugin and trying to use composer to auto load my classes, but I'm unable to get it working. I know there are a lot of questions on this topic but nothing seems to work for me.

directory structure:

composer.json file:

{
    "require": {
        "katzgrau/klogger": "dev-master"
    },
    "autoload": {
        "psr-4": { "Foo\\": "classes" }
    }
}

plugin-name.php file:

namespace Plugins_Main;

use Foo\Class_Name;

require 'vendor/autoload.php';

class Plugin_Name_Bootstrap{
    public static function run() {
        Class_Name::instance();
    }
 }
add_action('plugins_loaded', array('Plugins_Main\Plugin_Name_Bootstrap', 'run'));

Class_Name.php file:

namespace Foo;

class Class_Name{
    protected static $_instance = null;

    public static function instance(){
        if ( self::$_instance === null ) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}

According to the docs this autoloading should work, but I'm still getting

Class 'Foo\Class_Name' not found

I thought maybe it related somehow to the fact that I'm trying to initialize "Class_Name" in plugins_loaded hook, But why would that matter if I'm require vendor/autoload.php much earlier?

Upvotes: 3

Views: 2308

Answers (1)

Avishay28
Avishay28

Reputation: 2456

Needed to require autoload.php with __DIR__:

from

require 'vendor/autoload.php';

to

require __DIR__  . '/vendor/autoload.php';

Thanks Damian Dziaduch for the answer.

Upvotes: 5

Related Questions