1

Is there a way to find out a method which is called from a chain or not?

For example:

<?php ... class db { function query($sql) { //do query return $this; } } 

in the code above, How can I make sure from the class db that the the query() method is in chain or not?

$obj = new db(); $obj->dosth()->query(); 

or

$obj = new db(); $obj->query(); 
3
  • Do you want to "make sure" it is chained, meaning, it is ALWAYS called first? If so, the remove chaining all together and call dosth() in your query method Commented May 13, 2014 at 21:06
  • I merely wanna make sure is my query method in chain or not. Commented May 13, 2014 at 21:12
  • It's either in chain or not. So if you want to make sure, it's always one or the other, and there's nothing to make sure of. Commented May 13, 2014 at 21:16

2 Answers 2

1

You can't, and you probably wouldn't want to even if you could.

You can't

There is no way to either determine if a method is going to be called later in the chain or force the caller to do so. In addition, PHP does not have any mechanism or constructs that allow you to execute code automatically at certain points (such as RAII in C++ or using in C#).

You probably wouldn't want to

A big advantage of fluent interfaces is that they are composable:

$query = $db->doSth(); foo($query); function foo($query) { $query->doSthElse()->query(); } 

If you somehow forced the user to call query at the end of the statement, the general-purpose function foo could not exist.

See also

You might also find my answer to How to create a fluent query interface? useful -- there's nothing in there directly related to your question that I did not mention here, but "Step 3: Materializing" deals specifically with this part the interface.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the response and the links.
0

There's no chance to track how this method was called. I also don't see any reason why you should do it. Using chaining method should work exact the same as you call 2 (or more) methods separately.

I've checked it using debug_backtrace as in code above:

<?php class db { function query($sql) { $debug = debug_backtrace(); var_dump($debug); } function dosth() { return $this; } } $obj = new db(); $obj->dosth()->query("test"); echo "<br /><br /><br /><br />"; $obj2= new db(); $obj2->query("test2"); 

And in both calls there is exact the same debug info (of course except line where function was called)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.