Re: Updating inherited attributes without __construct()

From: Date: Sat, 07 Jun 2008 05:23:05 +0000
Subject: Re: Updating inherited attributes without __construct()
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-275110@lists.php.net to get a copy of this message
On Fri, Jun 6, 2008 at 2:09 PM, Tyson Vanover <tvanover@pdx.edu> wrote: > Sorry, I probably should have included the add() function from the parent. > As well as all of the parent constructor. > > Basically the object takes an array of key=>value pairs and parses them > into a string for output. When it takes in the array of pairs it needs to > check the keys against a list of valid keys. I have no preference on how to > store the list of valid keys other than to add more a constructor doesn't > need to be called. > > class parent{ > $validkeys = 'name,size'; > $attributes = array(); > > __construct($set){ > foreach($set as $key=>$value){ > if(isValidKey($key)){ > $this->attributes[$key] = $value; > } > } > } > > __toString(){ > $output = ""; > foreach($this->attributes as $key=>value){ > $output .= sprintf(TEMPLATE, $key, $value); > } > } > > __set($key, $value){ > if(isValidKey($key)){ > $this->attributes[$key] = $value; > } > } > > isValidKey($key){ > ...Something goes here... > } > } > > class child extends parent{ > ...All this needs to do is tack on values 'color,shape' to parent's valid > keys... > } > > class grandchild extends child{ > ...All this needs to do is tack on values 'cost,location' to child's valid > keys... > } > > Most sub classes won't need anything different from their parent but the > expanded list of valid keys. perhaps instead of subclassing you could write a set of decorators, with a base decorator, that the others extend. something like this, class BaseParentDecorator { protected $additionalValidKeys = array(); protected $theParent = null; public function __construct($parent) { $this->theParent = $parent; } public function __toString() { return $this->theParent->__toString(); } public function __set($key, $value) { $this->theParent->$key = $value; } public function isKeyValid($key) { /// determine if key is valid, by looking at $this->validKeys /// put that boolean result in a variable, like $isKeyValid, then return $isKeyValid || $this->theParent->isKeyValid($key); } } and now, instead of subclassing parent, to a potentially deep hierarchy, all your new classes will subclass BaseParentDecorator, so working off your example from above, we would have something like, class child extends BaseParentDecorator { protected $validKeys = array(/* tacked on values for child */); } class grandchild extends BaseParentDecorator { protected $validKeys = array(/* tacked on values for grandchild */); } then at runtime you simply wrap a child instance by the grandchild instance, as in $thing = new grandchild(new child(new parent(array(/* stuff */))); -nathan

« previous php.general (#275110) next »