slier
slier

Reputation: 6740

Restrict method chaining on other method

Let say i have this class

class Test
{

   method_a(){ return $this;}

   method_b(){ return $this;}

   method_c(){ return $this;}
}

$obj = new Test();
$obj->method_a()->method_b();
$obj->method_a()->method_c();
$obj->method_b()->method_c(); //i want to disallow this

How can i disallow method_b() chaining with method_c()

Edited:

Calling $obj->method_b() and follow by $obj->method_c() also disallow because i only want method_b chaining with method_a and method_c with other method

Upvotes: 2

Views: 123

Answers (2)

Gordon
Gordon

Reputation: 316969

You could use a State Pattern and introduce State objects for each possible state in Test. When someone calls Method B, you change the state of Test internally to the StateB class and when someone calls Method C then you can raise an Exception.

See http://sourcemaking.com/design_patterns/state

Upvotes: 1

oezi
oezi

Reputation: 51797

there are two possibilitys i can think of. the first is to not retun $this from method_b(). that would prevent chaining method_c() - but everything else, too, so this doesn't seem to be what you're looking for.

the second one is kind of ugly, but might work as intended: add another private variable $last_method to your class and set that in every called method (to the methods name or some kind of id). that way, when calling method_c(), you could check if the last called method was method_b() - and if so, throw an exception (or whatever you'd like to do in such a case). note that this solution would also prevent from calling method_b() and method_c() consecutive on the same object without chaining - so this might not be 100% what you're looking for.

Upvotes: 4

Related Questions