jeudi 2 mai 2019

PHP design pattern for conditional instantiation of classes

I'm looking for best practices in the following scenario (using Laravel, but that's not relevant): I have a method strokePet, which depending on the request payload, will instantiate a DogStroker or a CatStroker class. The strokePet method is called via an API endpoint.

class PetController
{
    public function strokePet($request)
    {
        if ($request->pet == 'dog') {
            $stroker = new DogStroker;
        else if ($request->pet == 'cat') {
            $stroker = new CatStroker;
        } 
        $stroker->stroke();
    }
}

class DogStroker
{
    public function stroke()
    {
        echo 'grr';
    }
}

class CatStroker
{
    public function stroke()
    {
        echo 'prr';
    }
}

Is there any advantage in creating a PetStroker interface, e.g.

interface PetStroker
{
    public function stroke();
}

or is there some design pattern I'm missing here which would make this more OOP-idiomatic? (I'm aware this may get flagged for being too vague.)

Aucun commentaire:

Enregistrer un commentaire