Type of safe universal decorator in PHP

I would like to create a generic decorator log that is type safe.

I have a number of repositories (interfaces), and you need a decorator for anyone who catches exceptions that they can throw, passes their instance to LoggerInterface , and then iterates through them. You can create a special decorator and test for everyone, although this is rather cumbersome (it is especially good to test) and something that I prefer to avoid.

Using it __callto create a more general decorator is the first approach that comes to mind. However, this leads to an instance of the object that does not implement the repository interface that it adorns. This is not an option for my project. Is there a way to tell PHP that it implements this interface, for example, using reflection magic ?

I read “ how to implement a decorator in PHP? ” And “The best way to implement a decorator for caching method results in PHP ” here in stackoverflow, both of which stand for a dedicated and general approach, although they do not give instructions for a general approach safe type. Some time has passed since the issues that were published, so perhaps everything has changed. I am using PHP 7 and can use PHP 7.1 if necessary.

PHPUnit_MockObject allows you to build an object that implements the interface through the same code that is called by a familiar method getMockin PHPUnit. This can be the basis of a common decorator. However, this will require the use of a mocking library in production code. In addition, this library internally uses eval to do its job. This will disqualify him for my project.

+4
source share
3 answers

, , - Decorator, . :

interface FooInterface {
    function doFoo();
    function doMoreFoo();
}

class Foo implements FooInterface {
    public function __construct() {}
    public function doFoo() {}
    public function moreFoo() {}
}

class FooDecoratorBase implements FooInterface {
    protected $foo;
    public function __construct(FooInterface $foo) { $this->foo = $foo; }
    public function doFoo() { $this->foo->doFoo(); }
    public function moreFoo() { $this->foo->moreFoo(); }
}

class ExtraFooDecorator extends FooDecoratorBase {
    public function extraFoo() {}
}

, PHP, , Reflections - , /, .

0

"Generic TypeParameters" PHP ( HHVM Facebook). . @Sammitch - , .

.

. , , ( ).

Please consider what your Decorator will look like:

function DoSomeOperation() {
    try {
        return $this->decoratedObject->DoSomeOperation(); //Object is injected in Decorators Constructor
    catch (\Exception $ex) {
        Logger::Log($ex);
        throw;
    }
}

Why not just do it without a decorator in your repository:

function DoSomeOperation() {
    try {
        //Do The Logic
    catch (\Exception $ex) {
        Logger::Log($ex);
        throw;
    }
}

But maybe the Decorator / Wrapper for the PDO object is what you really want to have? (ᵔᴥᵔ)

0
source

All Articles