user1620152
user1620152

Reputation: 134

What is the best practice within yii2 to create a factory class?

So basically, I want to create implement a factory class that will use a couple different models. I don't have a clue as to how I should go about doing this within yii2. Any help would be nice.

Here is a general idea of what I am trying to do. use app\models\Event; use app\models\EventParticipant; use app\models\Match;

/**
 * @property Event $Event
 * @property EventParticipant $EventParticipant
 * @property Match $Match
 */
abstract class Tournament
{
    protected $_id;
    protected $_event;
    protected $_type;

    final public function __construct($event) {
        $this->Event = new Event();
        $this->EventParticipant = new EventParticipant();
        $this->Match = new Match();

        if(!$event) {
            throw new \yii\web\HttpException(400, 'Invalid Event', 405);
        }

        $this->_id = $event['Event']['id'];
    }
}

}

Upvotes: 2

Views: 1569

Answers (1)

Amigo Nikola
Amigo Nikola

Reputation: 46

I would avoid throwing Http exceptions in models, use them in Controllers. You can throw InvalidConfigurationException for example, not necessary as you need to have $event.

There are many implementations of Factory design pattern, here is the simplest

class TournamentFactory
{
    public static function create(Event $event, EventParticipant $eventParticipant, Match $match) {
        return new Tournament($event, $eventParticipant, $match);
    }
}

but I don't see it's use in this example. I mostly use it to switch between object types, something like this, in your example:

$grandSlam = TournamentFacory::create('grandSlam');
$grandSlam->setEvent($event);
$grandSlam->setParticipants($participants);
...
$masters = TournamentFacory::create('masters');
...

these objects might have same properties in common, but different implementations. For example masters are played to two winning sets, grand slams on 3...etc...

Upvotes: 1

Related Questions