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();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
vandaad
  • 39
  • 4

2 Answers2

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.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
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)

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291