douxiao0400 2015-12-08 17:00
浏览 25
已采纳

通过作曲家覆盖课程

I'm using a composer Library, with lots of classes. There is one class (Alibrary\FileA) in this which doesn't do exactly what I want it to do.

namespace Alibrary;

class FileA
{
    public function sayHello()
    {
        echo 'hello';
    }
}

So I've written a replacement called Mylibrary\FileB. As you can see it's so must better.

namespace MyLibrary;

use \Alibrary\FileA;

class FileB extends FileA
{
    public function sayHello()
    {
        echo 'hi';
    }
}

Is there any way to tell Composer to load FileB every time FileA is asked for? I just want to replace one class, basically for testing purposes. I don't want to create a whole new repo - I've looked at https://getcomposer.org/doc/04-schema.md#replace already.

Is there something like this that I can do?

"classmap": [
    "\Alibrary\FileA": "MyLibrary\FileB"
],

Thanks.

  • 写回答

1条回答 默认 最新

  • dongtieshang5429 2015-12-09 23:47
    关注

    Your question has not very much to do with Composer in particular, but with how PHP works in general - and the code you are using.

    Autoloading gets the name of the class that is still unknown to PHP and has to find the code that defines this class. But the situation you are facing would be the same if all classes are in one single file: The code is using class \Alibrary\FileA, and is not using class \MyLibrary\FileB. Note that your invented class names do suggest you are thinking in files, which is not the primary effect. Yes, classes' code is usually stored in files, but as soon as the code is loaded by PHP, it is only "the class" that is relevant, not where the code came from.

    So you have some classes that do something, and one of them is \Alibrary\FileA. How can you change this to your own class? It depends. If the code creates that FileA class itself, you cannot override it from outside. If the code wants you to pass an instance of FileA as a parameter, you can instead pass your FileB class that inherits from FileA and must implement all that methods with the same parameter signature, and must return the same types. If it returns something completely different, it may work, but is likely to break.

    Note that inheriting another class is in itself likely to break if you update the original library.

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

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化