tags:

views:

50

answers:

2

I am building some kind of a proxy pattern class for lazyloading sql queries.

the proxy pattern uses __call, __get and __set for relaying calls on its object, but sometimes there is no object, if the sql did not return any rows.

my question is then, if i do a is_null() on the proxy class, is it possible to make the class return true then? I am thinking is there any SPL interface I can implement like Countable which makes the class work in count().

Any suggestions?

+2  A: 

Sadly, this is not possible I'm afraid for a object passed to is_null to return true. Some alternative might be to:

1) Use NullObjects, an interesting discussion on these can be found recently on sitepoint http://www.sitepoint.com/forums/showthread.php?t=630292

2) Actually return null rather than an object, although this may not be possible in your situation.

Rob Tuley
I was pretty sure it was not possible, but had to ask :)NullObjects is interesting, but i am trying to make i datamapper setup, that completely seperates DB from Domain logic, and by using NullObjects, the code using my Domain models, would need to be aware of this.I am probaly going for #2 that still requires my domain models to extend a base entity class, not perfect, but okay.thanks for your input.
SuneKibs
A: 

I don't know if this is of any help but by taking advantage of the __toString method you could possible achieve what you are looking for, but be warned, this is not at all clean code or best practice, the solution Rob suggested is actually better

You have to be using PHP5.2 or higher and take advantage of typecasting and the __toString magic method of PHP's class model

class Dummy 
{
 private $value;

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

 public function __toString()
 {
  return $this->value;
 }
}

$dummy = new Dummy('1');
if((string)$dummy) {
 echo "__toString evaluated as true".PHP_EOL;
} else {
 echo "__toString evaluated as false".PHP_EOL;
}

$dummy2 = new Dummy('0');
if((string)$dummy2) {
 echo "__toString evaluated as true".PHP_EOL;
} else {
 echo "__toString evaluated as false".PHP_EOL;
}

What happens here is the __toString method returns either the string 0 or string 1 (attention, don't return integers, return strings!)

'0' evaluates to false, '1' evaluates to true in if statement so it might be of help in your case too.

ChrisR
__toString also crossed my mind, but would not do entirely what i wanted, but thank you very much for your comment
SuneKibs