douyu9159 2017-04-30 14:45
浏览 41
已采纳

如何使用自己的作曲家自动加载另一个包

EDIT with important note: The package I want to include does not use composer autoload. I'd have to use their hacky one and I want to avoid that.

I know how composer mostly works and I have package that can be a dependency (that's important, I know how to make this work in one project, but that's not what I'm asking).

What I need?

  1. Somebody requires my package

    composer require tomas/my-package

  2. It will install

  3. It will autoload my package with PSR-4

  4. It will autoload 3rd party package as well

I have already tried something like this:

"autoload": {
    "psr-4": {
        "MyPackage\\": "src",
        "PHP_CodeSniffer\\": "../../squizlabs/php_codesniffer/src"
    }
}

I've tried that in one of my dependencies and it doesn't work :(.

Also, I've already talked to the package author and he doesn't want to use composer autoloading. He prefers his own.

Thanks for any help!

  • 写回答

2条回答 默认 最新

  • doupai1876 2017-05-08 10:10
    关注

    None if these answer are related to problem I desribed, so I try to post best solution so far:

    I got inspired in PHPStan, which has feture to autoload directories, that were missed in composer (practically same issue).

    I've added RobotLoader:

    composer require nette/robot-loader
    

    Then create LegacyCompatibility class with static method:

    use Nette\Loaders\RobotLoader;
    
    // ...
    
    public static function autoloadCodeSniffer(): void
    {
        $robotLoader = new RobotLoader;
        $robotLoader->acceptFiles = '*.php';
        $robotLoader->setTempDirectory(sys_get_temp_dir() . '/_robot_loader');
        $robotLoader->addDirectory(getcwd() . '/vendor/squizlabs/php_codesniffer/src');
        $robotLoader->register();
    }
    

    And I call it, when needed:

    LegacyCompatibility::autoloadCodeSniffer()
    

    Works like a charm. But still opened to better solutions +1 !

    Github Permalink

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?