Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...