Jump to content

Helper class definition - is this example good or bad?


antmeeks

Recommended Posts

So I've decided to put several disparate but related functions into helper classes. Here's an example of what such a class would look like (with obviously more involved methods), and I'd like a critique on it's structure.

 

class MyHelpers {

public $str;

public $Array;

private $Params;

public function __construct($method, $Params) {

	$method = '_' . $method;

	$this->Params = (is_array($Params)) ? $Params : NULL;

	$result = (method_exists($this, $method)) ? $this->$method() : NULL;

	(is_array($result)) ? $this->Array = $result : $this->str = $result;

}

private function _outputString() {

	if(is_array($this->Params)) : 

		return (isset($this->Params['str'])) ? $this->Params['str'] : NULL;

	endif;

}

private function _makeArray() {

	if(is_array($this->Params)) :

		$str = (isset($this->Params['array'])) ? $this->Params['array'] : NULL;

		return explode(',', $str);

	endif;
}

}

 

And here's how you would instantiate and use it:

 

$GetResult = new MyHelpers('outputString', array('str'=>'This is a string.'));

$str = $GetResult->str;

$GetResult = new MyHelpers('makeArray', array('array'=>'1,2,3'));

$Array = $GetResult->Array;

 

Thoughts?

#1 can be easily solved with sticking the functions in a file in a well-known place, but #2 is actually one of the few decent reasons.

 

Use static methods, not instance methods. Make the class a mere container of functions, not an object of sorts.

class MyHelpers {

public static function makeArray($array) {
	return explode(',', $array);
}

public static function outputString($str) {
	return $str;
}

}

#1 can be easily solved with sticking the functions in a file in a well-known place, but #2 is actually one of the few decent reasons.

 

I did have them organized in a separate files, but wanted to eliminate as many manual includes/requires as possible.

 

Use static methods, not instance methods. Make the class a mere container of functions, not an object of sorts.

 

Sigh... Yes, you are probably right - that's the best approach... I guess I was just trying to be too clever... I suspected it was dumb, which is why I posted it, lol.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.