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.
EDIT
- Changed comments to code.
- This is a model (and a corresponding table in the DB) that has more data than just a
pictureandquote. Example,descriptionthat’s part of thepostand doesn’t reside on either thepictureor thequote. - There’s tables for
pictures andquotes. - Using PHP Active Record and each of the three classes extends the generic model class provided by PHP Active Record.
- The
picturemodel has it’s own data. Same forquote.
To expand on the idea of the Strategy pattern mentioned in the comments:
Each strategy would presumably implement the same interface as the
Postclass 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.