Composer class not found fatal error – wordpress plugin development

I am trying to use composer to autoload my classes in a wordpress plugin.

I wish for my models and controllers to reside within the GD namespace, however I would like to put my models and controllers into their own directories.

Read More

I am facing the error message: Fatal error: Class 'GDShortcodeController' not found in /.. .../src/GD/App.php on line 10

directory/file structure

plugins
    gd
        cache
            // location for twig template cache
        public
            // location for plugin assets
        src
            controllers
                ShortcodeController.php
            models
            App.php
        templates
            test.html
        vendor
            // location for application dependencies installed via composer
            composer
                autoload_namespaces.php

composer.json

{
    "require": {
        "twig/twig": "1.*"
    },
    "autoload": {
        "psr-0": {
            "GD": ["src/", "src/GD/", "src/GD/controllers/", "src/GD/models/"]
        }
    }
}

vendor/composer/autoload_namespaces.php

return array(
    'Twig_' => array($vendorDir . '/twig/twig/lib'),
    'GD' => array($baseDir . '/src', $baseDir . '/src/GD', $baseDir . '/src/GD/controllers', $baseDir . '/src/GD/models'),
);

GD/src/App.php

class App
{
    private $plugin_dir;
    private $twig;

    public function init()
    {
        $shortcodes = new ShortcodeController;
        add_shortcode( 'gd', [ $shortcodes , 'gd'] );
    }
}

GD/src/controllers/ShortcodeController.php

<?php namespace GD;

class ShortcodeController
{
    // STUFF IN HERE
}

Should i be using autoload classmap instead of psr-0? How does composer deal with namespaced classes when using classmap?

Related posts

Leave a Reply

1 comment

  1. You have "src/GD/controllers/" in your psr-0 here

    "autoload": {
        "psr-0": {
            "GD": ["src/", "src/GD/", "src/GD/controllers/", "src/GD/models/"]
        }
    }
    

    But ShortcodeController.php file in GD/src/controllers folder and namespace is

    <?php namespace GD;
    
    class ShortcodeController
    {
        // STUFF IN HERE
    }
    

    So, your ShortcodeController.php should be in the src/GD/controllers/gd folder but right now the path is GD/src/controllers/ShortcodeController.php and Autoloader is looking in to "src/GD/controllers/gd/ShortcodeController.php" folder (including other entries in the array) or you can change "src/GD/controllers/" to "GD/src/controllers/" in psr-0. Also, you are using shortcodes = new ShortcodeController; from root/global namespace so, it could be

    shortcodes = new GDShortcodeController;
    

    According to

    "autoload": {
        "psr-0": {"GD": "GD/src/controllers/"}
    }
    

    your Class

    <?php namespace GD;
    
    class ShortcodeController
    {
        // STUFF IN HERE
    }
    

    Should be in GD/src/controllers/gd folder.