k0pernikus
k0pernikus

Reputation: 66730

How to replace a class with a custom class in php?

Given an external dependency within a [email protected] project (without composer):

interface Contract
{
    public static function getFoo(): string;
}

class ExternalDependency implements Contract
{

    public static function getFoo(): string
    {
        return 'gnarf!';
    }
}

That ExternalDependecy is used in dozen other services like so:

class Service extends ExternalDependency {
}

I want to replace ExternalDependency while changing as little code as possible.

I thought I could make use of a class_alias:

class MyFix implements Contract {
    public static function getFoo(): string {
        return 'Foo';
    }
}

class_alias(MyFix::class, SomeExternalDependency::class);

class Service extends SomeExternalDependency {
}

Yet this will issue a warning:

PHP Warning:  Cannot declare class SomeExternalDependency, because the name is already in use in test.php on line 23

In my contrived example, I could delete the ExternalDependency, then it would work as expected. Yet in my actual use-case, the ExternalDependency is a vendor file that I cannot delete easily. (It is sourced from an external path on the server.)

How to replace the ExternalDependency with MyFix then?


Example on onlinephp.io


This question is related, yet all its answers are based on extending the to be replaced class or or lack detail.

Upvotes: 0

Views: 69

Answers (1)

k0pernikus
k0pernikus

Reputation: 66730

I found a workable approach using traits. While I have to add the use MyFix line to a dozen of services, the fix itself is at least stored in one place in the codebase.

I still prefer to completely replace the class, yet this works good enough.

<?php

interface Contract
{
    public static function getFoo(): string;
}

class ExternalDependency implements Contract
{

    public static function getFoo(): string
    {
        return 'gnarf!';
    }
}

trait MyFix
{
    public static function getFoo(): string
    {
        return 'Foo';
    }
}


class Service extends ExternalDependency
{
    use MyFix;
}

var_dump(Service::getFoo());
var_dump(Service::getFoo() === 'Foo');

Upvotes: 0

Related Questions