mardi 21 avril 2015

Object property setters are regulated depending on context. Any OOP solution?

class SomeObject {

    protected $foo,
              $bar;

    protected $context;

    public function __construct($context) {
        $this->context = $context;
    }

    public function setFoo($val) {
        if ($this->context == 'public') {
            throw new \Exception('It is impossible to modify foo property in public context!');
        }
        $this->foo = $val;
    }

    public function setBar($val) {
        if ($this->context == 'api') {
            throw new \Exception('It is impossible to modify bar property in API context!');
        }
        $this->bar = $val;
    }

}

As you can see from this piece of "code" - object restricts setters depending on context value. This code is really hard to maintain. How can we rewrite it to make it beautiful and easy maintainable?

My thoughts are:

  • Make $context an object(s) implementing interface isAllowed($object, $propertyName).
  • After making $context an object we have to thing about how can we store "restrictions" in $context object taking in mind there are a lot of different objects similar to SomeObject.
  • In every setter I should check $this->context->isAllowed($this, 'foo') - it looks not good. So, probably we want to add some "proxy" over SomeObject?
  • Passing $context to constructor also seems rather ugly for me.

What's your ideas about it?

Aucun commentaire:

Enregistrer un commentaire