Give me feedback

Php object design - good practise to set attributes

I have this class (taken from someone else project)

class Config
{
protected $database = array();
protected $hashMethod = 'bcrypt';
protected $defaultRounds = 8;
protected $randomRounds = false;
protected $minRounds = 5;
protected $maxRounds = 9;
//and 30+ other attributes
}

PHPMD guidelines say that an object shouldn't have more than 15 attributes. What would be a good solution to improve this object?

I think that something like this can be considered PHPMD compliant

class Config
{
protected function getDefaultAttributes()
{
//$def_attributes might be taken from a config file or from a database ...
$def_attributes = array();
$def_attributes['database'] = array('a' => 1);
$def_attributes['hashMethod'] = 'bcrypt';
$def_attributes['defaultRounds'] = 8;
$def_attributes['randomRounds'] = false;
$def_attributes['minRounds'] = 5;
$def_attributes['maxRounds'] = 9;
//[...]

return $def_attributes;
}

protected function getDefaultAttributeValue($attribute)
{
$def_attributes = $this->getDefaultAttributes();
return $def_attributes[$attribute];
}

protected function validateObjAttr($attribute, $value)
{
//attribute not found in the attributes list
if ( ! in_array($attribute, array_keys($this->getDefaultAttributes()))) {
return false;
}

//attribute should be an array
if ( is_array($this->getDefaultAttributeValue($attribute)) && ! is_array($value)) {
return false;
}

//attribute should be an object
if ( is_object($this->getDefaultAttributeValue($attribute)) && ! is_object($value)) {
return false;
}

return true;
}

public function __set($attribute, $value)
{
if ($this->validateObjAttr($attribute, $value)) {
$this->$attribute = $value;
}
}

public function __get($attribute)
{
if (isset($this->$attribute)) {
return $this->$attribute;
}

return null;
}
}

Is it a good idea? Can be improved? Suggestions?

Reactions 0 reactions

No reactions yet, be the first: comment or tweak the code

Comment on this code:

Please Login or Register to leave a comment.