OOP Problem: Is there is a design pattern for this?

class PicGenerator {

function __construct()
{
$gallery = new Gallery(‘dogs’)
$array = $gallery->getArrayOfPics(); //either returns an array of pics or false
}

function countImages {};
function resizeImages{};
}

Suppose I have a class like the one above. When I call $gallery->getArrayOfPics(); I should get an array of dog pictures, or just a bool (false).

If I get a return value of bool (false), I don’t want the countImages{} or resizeImages{} method to work… but I don’t want to have to check if $array === false everytime in each method. Is there some sort of design pattern for situations like this, where if a certain value is false, all of the methods will just return false if they are called?

Also is creating an object inside inside the constructor considered bad loose coupling?
thanks,

Thanks PCSpectra,
I’m reading up on dependency injection now.

If I get a return value of bool (false), I don’t want the countImages{} or resizeImages{} method to work… but I don’t want to have to check if $array === false everytime in each method. Is there some sort of design pattern for situations like this, where if a certain value is false, all of the methods will just return false if they are called?

I would test for a count() greater than ZERO in each method and return FALSE if it’s ZERO, otherwise return the array, etc.

Also is creating an object inside inside the constructor considered bad loose coupling?

It creates a concrete dependency which increases the coupling, yes. Injection would result in a more abstract dependency, and looser coupling. I would leave it as is, until you realize the benefits of injecting the object in to the ctor().

Cheers,
Alex

It took me a few minutes of looking at Proxy to get whats going on. You seem have a db connection you’re using to pull data, you create an object of the class you’re controlling, and control it via __call. Thanks for this.

Check out the Proxy Design Pattern. :wink:


<?php
class DataSource implements Countable
{
  protected
    $photos = array();
    
  public function __construct(array $photos = array()){
    $this->photos = $this->photos + $photos;
  }
  
  public function count(){
    return count($this->photos);
  }
}

class Proxy
{
  protected
    $datasource;
    
  public function __construct($datasource){
    $this->datasource = $datasource;
  }

  public function __call($method, $args = array()){
    if(is_callable(array($this->datasource, $method)) && 0 < count($this->datasource)){
      return call_user_func_array(array($this->datasource, $method), $args);
    }
    return false;
  }
}
?>


$photos = new DataSource();

var_dump(
  $photos->count() #0
);


$photos = new Proxy(new DataSource());

var_dump(
  $photos->count() #false
);