Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.