Give me feedback

Php object design - good practise to set attributes

I have this Config class, taken from someone else project, and I'm trying to refactor it as an exercise.

PHPMD guidelines say that an object shouldn't have more than 15 attributes. So I started working on this aspect and I'm looking for a good solution to improve the object.

I will attach the original code and my code.

Is my code a good idea? Can be improved? Suggestions?

untitled.php
/** * Original class */ class Config { protected $database = array(); protected $hashMethod = 'bcrypt'; protected $defaultRounds = 8; protected $randomRounds = false; protected $minRounds = 5; protected $maxRounds = 9; //and 30+ other attributes }
untitled.php
/** * My class */ 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; } }

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.