Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern for repetitive switch in getters?

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 picture and quote. Example, description that's part of the post and doesn't reside on either the picture or the quote.
  • There's tables for pictures and quotes.
  • Using PHP Active Record and each of the three classes extends the generic model class provided by PHP Active Record.
  • The picture model has it's own data. Same for quote.
like image 638
Jungle Hunter Avatar asked Nov 05 '22 01:11

Jungle Hunter


1 Answers

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.

like image 103
cmbuckley Avatar answered Nov 09 '22 07:11

cmbuckley