dimanche 28 décembre 2014

Extend Class - Or pass new Instance in a Constructor?


I'm working on a project and I've built my classes in 2 ways, I'm after opinions on which you think should be used, and why.


I have a Finder class. This essentially builds a path, based on the Finder file type. CSS.


Should my CSS class extend Finder? Or should CSS be passed to Finder (in a constructor for example)?


Below is a very basic example of my classes, just to give you an idea. They both work as expected and give the same results, but I'm sure there's a preferred approach.


Extends



class Finder {

private $filename;

public function filename($filename){
$this->filename = $filename;
return $this;
}

public function path(){
return $this->sharedDirectory() . $this->filename . $this->extension();
}
}



class CSS extends Finder {

public function extension(){
return '.css';
}

public function sharedDirectory(){
return '/assets/public/';
}
}



$finder = new CSS();
$finder->filename('example');
$path = $finder->path();

var_dump($path);


Constructor



class Finder {

private $filename;

private $item;

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

public function filename($filename){
$this->filename = $filename;
return $this;
}

public function path(){
return $this->item->sharedDirectory() . $this->filename . $this->item->extension();
}
}


class CSS {

public function extension(){
return '.css';
}

public function sharedDirectory(){
return '/assets/public/';
}
}


$finder = new Finder(new CSS);
$finder->filename('example');
$path = $finder->path();

var_dump($path);


Plus points so far


"Constructor" method, I can specify an interface in __construct(), so all my Finder sub-types adhere to the same structure.


"Extends" method, I can easy overwrite/intercept parent methods by creating the same method name in the child class. For example, a subclass of Javascript could manipulate the filename given to filename(). Leaving this logic out of the parent Finder class, as it would only happen on certain child classes.


Any feedback is appreciated,


Thanks, Adrian





Aucun commentaire:

Enregistrer un commentaire