Using spl_autoloading within WordPress plugin

I’m struggling with spl_autoloading inside a namespaced WordPress Plugin.

I already revised these questions:

  • https://stackoverflow.com/questions/17806301/best-way-to-autoload-classes-in-php

  • https://stackoverflow.com/questions/29847329/wordpress-plugin-with-classes-namespaces-and-psr-0-autoloading

My folder structure looks like that:

Namespacing everything below SamplePlugin

inside wp-content/plugins/sample-plugin

    src
     '-- SamplePlugin
     '   '-- ShortCode.php
     '-- autoload.php
    sample-plugin.php

My current autoload function (as I’m used to doing it…)

spl_autoload_register(function ($class) {

$dir="src/";
$file = str_replace('\\', "https://wordpress.stackexchange.com/", $class) . '.php';

require_once $dir . $file;

Using that, the prefixing namespace is correctly added, so if I instantiate in sample-plugin.php:

namespace SamplePlugin;
require_once 'src/autoload.php';

$shortcode = new ShortCode();

I get the following output (VVV):

Warning: require_once(src/SamplePlugin/ShortCode.php): failed to open stream: No such file or directory in /srv/www/wordpress-default/wp-content/plugins/sample-plugin/src/autoload.php on line 8

Fatal error: require_once(): Failed opening required ‘src/SamplePlugin/ShortCode.php’ (include_path=”.:/usr/share/php:/usr/share/pear”) in /srv/www/wordpress-default/wp-content/plugins/sample-plugin/src/autoload.php on line 8

Any hints?

All Classes (e.g. ShortCode are callable through SamplePlugin\Shortcode.

1 Answer
1

I think the problem here is that you’re using a relative path in autoload.php inside the src/ subfolder,

Try for example to modify your src/autoload.php to use absolute paths instead:

\spl_autoload_register( function( $class )
{
    $dir = plugin_dir_path( __FILE__ );

    $file = str_replace( '\\', "https://wordpress.stackexchange.com/", $class ) . '.php';

    $path = $dir . $file;

    if( file_exists( $path ) )
        require_once $path;

} );

where we add a file_exists to be plugin class specific.

Update

Here’s the main /sample-plugin/sample-plugin.php file:

<?php
/**
 * Plugin Name: Sample Plugin
 */

namespace SamplePlugin;

require_once __DIR__ . '/src/autoload.php';
// require_once 'src/autoload.php';

$shortcode = new ShortCode();

Here’s the /simple-plugin/src/SamplePlugin/Shortcode.php file:

<?php
/**
 * Class Shortcode
 */

namespace SamplePlugin;

class Shortcode
{
    public function __construct()
    {
        print 'DEBUG: Greetings from the Shortcode instance!';
    }
}

You could also check out how Composer generates the vendor/autoload.php file, that’s included with:

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

Leave a Comment