Autoloader for distributed PHP plugins that includ

2019-09-19 13:41发布

问题:

I am working with a CMS that requires the user to upload extensions.

The users do not have access to composer. So I will need to include the dependencies in the distribution itself.

Would how I implement it work for autoloading all dependencies? Is this the way to go about this?

Here's the simplified directory structure of the distributed extension. (The user is supposed to upload the contents of the upload directory):

upload/Eg/
upload/Eg/autoload.php <-- autoloader to load the dependencies
upload/Eg/MyClass.php <-- requires autoload.php
upload/Eg/dependencies <-- where required composer packages are copied
upload/Eg/dependencies/guzzlehttp <-- for example

autoload.php

spl_autoload_register(function ($className)
{
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strripos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

    require $fileName;
});

MyClass.php

namespace Eg;

require './autoload.php';

use GuzzleHttp;

class MyClass {
}

Side note: The application I am writing actually "builds" the extension automatically. The copying of dependencies from composer's "vendor" folder is done automatically.

回答1:

The users do not have access to composer. So I will need to include the dependencies in the distribution itself.

You are reinventing the wheel here. Composer is open source so I'd simply take a look and check if I can reuse its code and logic. You'd probably be able to easily get rid of 90% of the code, yet the autoloader and composer.json scanning should be all you need.