Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

Autoloader for distributed PHP plugins that includes composer packages

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...