mardi 28 novembre 2017

Check an object for interface which is not impemented

I am looking for a possibility to check, if an object fit to an interface, which is not implemented by the object.

Since composer changed the way of programming in php, you do not have access to all of the code you use.

For example you want to extend a composer project of yours. You want to manipulate an Collection. There are multiple classes, where you could use your new package. In some regions of your project, there are ArrayObject´s in other regions there are Collection´s with different interfaces. You want to get them all, but you can not manipulate all these old classes, because it´s legacy :) or a packagist package.

Thatswhy I am looking for a nice way to check, if an interface in one package fit to an object in an other package, which do not implement this interface.

// come from one package and I can not change the class
class FreshExample extends \ArrayObject
{
    public function doSomething(): string
    {
        return 'a new thing';
    }
}

// come from an other package and I can not change the class
class OldExample extends \ArrayIterator
{
    public function doSomething(): string
    {
        return 'a old thing';
    }
}

// my new package classes
interface ExampleInterface extends \Iterator
{
    public function doSomething(): string;
}

class WorkWithExamples
{
    /**
     * @param OldExample|FreshExample|ExampleInterface $example
     *
     * @return string
     */
    public function manipulate($example): string
    {
        // here I want to check if the incoming object fits to the interface
        if (false === $example->valid()) {
            return $example->doSomething();
        }

        return sprintf('%s!', $example->doSomething());
    }
}

One possibility would be, to use reflaction classes for the interface and the other objects, for a check, if both have the same methods, and so on.

An other way could be to use the decorator pattern.

Are there any other, or better way?

Aucun commentaire:

Enregistrer un commentaire