dongxian8858 2016-04-04 18:30
浏览 25
已采纳

我可以通过后备更改PSR 4 Autoload NameSpacing吗?

I have a public package on packagist/composer.

Originally it autoloaded with PSR-4 \GitHubUser\Package\Class for the file src/Class.php.

I would like to shorten this to \Package\Class for the same file. This is easily done by changing the composer.json. But is there a way I can do this with a fallback for people using the existing longer call? (autoload both?)

What I'd like:

"autoload": {
    "psr-4": {
        "PackageName\\": "src",
        "User\\OldPackageName\\": "src"
    }
}

But it doesn't register the 2nd call for the same folder.

  • 写回答

1条回答 默认 最新

  • douwei7501 2016-04-04 18:46
    关注

    You have to find a way that the one file that gets loaded defines the correct single class, or both classes. It might be doable, maybe duplicate the code, extend the class or something else.

    On the other hand, that's what incompatible update versions are for. You can try and support the old name forever, or you can cut this legacy and only support the new name (why did you change it in the first place?).

    Composer will not change the namespace line in the code, so the prefix in the autoloader cannot be changed at will - it has to be in the code. Also note that in order to be compatible to PSR4, referenced by PSR1, only one class per file is allowed.

    What is the goal of this attempt? In order to make the old package name avaibable to the public, you can decide to support the old version a little bit longer, i.e. apply functional and security fixes. The new version would be marked with a higher major version number, and also supported. A migration guide would point out that the only requirement to update is to change the namespace, anything else would be the same. This results in a much cleaner upgrade path, because you can test both versions individually, and don't forget about corner cases.

    Also you don't run into problems with type hinting, when a class from the old namespace has a typehint for the new class or vice versa (and this is likely impossible to change in code - at least it is way too uncommon that I want to think about a solution).

    TLDR: Use two major versions for the two namespace-incompatible packages, and provide the user with the easy-to-do upgrade instructions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私