dimanche 26 avril 2015

Bad practice to set private/protected methods to "public" during runtime

Okay I don't know if it's bad design but I feel a bit bad about doing the following:

abstract class A
{
    abstract public function getCallable(); 
}

class B extends A
{
    public function getCallable()
    {
        return array($this, 'doSomething');
    }

    protected function doSomething()
    {
        // Do stuff here
    }
}

The reason why B::doSomething is protected is that I don't like to expose this method because it should only be called from somewhere else in the code where I do a call_user_func() for the return value of B::getCallable.

You should be free to organize yourself in the subclasses of A. Without exposing anything to the outside. So the "API" won't change to the view outside of the subclasses of A.

So you should not be able to do something like:

$b = new B();
$b->doSomething();

the only way to get B::doSomething executed should be over:

$b = new B();
call_user_func($b->getCallable());

So I'm thinking about how I could achieve that. One way I could think of is create a ReflectionMethod object from B::getCallable()'s return value and set it to accessable if the method is not public.

I don't like this solution also it would work but is not that elegant:

class B extends A
{
    public function getCallable()
    {
        return function()
        {
            $this->doSomething();
        };
    }

    protected function doSomething()
    {
        // Do stuff here
    }
}

Any good suggestions or other ideas how to work around this?





Aucun commentaire:

Enregistrer un commentaire