通过作曲家覆盖课程

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.

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.