I've an ORM model (PHP Active Record), say, for a blogging system. I've something that's a post
model that stores the number of likes. The post
could either be a picture
or quote
(say), and they are different tables (and hence models).
The schema is that a post
holds data like number of shares, likes, description, etc. along with either a picture
or a quote
.
So when writing getters for the post
model I'm having to write
public function getX() {
if ($this->isPicture()) {
return $this->picture->getX();
}
else if ($this->isQuote()) {
return $this->quote->getX()
}
else {
return self::DEFAULT_X
}
}
I'm currently having to write this structure for many getter. Is there something I can do to avoid that?
PS: Tagged as PHP because that's my code in.
picture
and quote
. Example, description
that's part of the post
and doesn't reside on either the picture
or the quote
.picture
s and quote
s.picture
model has it's own data. Same for quote
.To expand on the idea of the Strategy pattern mentioned in the comments:
class Post {
// get the correct 'strategy'
public function getModel() {
if ($this->isPicture()) {
return $this->picture;
}
if ($this->isQuote()) {
return $this->quote;
}
return null;
}
// using the strategy
public function getX() {
$model = $this->getModel();
if (null === $model) {
return self::DEFAULT_X;
}
return $model->getX();
}
}
Each strategy would presumably implement the same interface as the Post
class for exposing those getters. Even better would be to provide a default strategy (rather than returning null) and have that return the default values. That way, the null check in each getter becomes redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With