mardi 22 janvier 2019

How can I avoid reflections when using polymorphism in PHP

I have a situation where I have a "Task" class that can "progress"

However each Task has different required param to know how to progress, and therefore the "progress" should receive different parameters.

What I did was making sure each "Task" implements an "ITask" interface which forces the implementaion of "progress" method. The parameter for the "prgoress" method is "ITaskProgress" interface, which will allow me to put the right task progress for each task.

The problem is I need to reflect the taskProgress inside the Task when I use it to progress, to know which members/method exists inside the "taskProgress" so I can use it to progress.

I don't feel this is the right way, how would you put the pieces together the right way?

Assume that because Task and Task Progress have to be saved in different places they cannot live under the same class.

interface ITaskProgress {};
interface ITask
{
    function progress(ITaskProgress $taskProgress);
}
class DoThisTaskPrgoress implements ITaskProgress
{
    public $needThisToProgress;
}

class DoThatTaskProgress implements ITaskProgress
{
    public $needThatToProgress;
    public $alsoNeeded;
}

class DoThisTask implements ITask
{

    function progress(ITaskProgress $taskProgress)
    {
        if ($taskProgress instanceof DoThisTaskPrgoress)
        {
            $taskProgress->needThisToProgress++;
        }
    }
}

class DoThatTask implements ITask
{
    function progress(ITaskProgress $taskProgress)
    {
        if ($taskProgress instanceof DoThatTaskProgress)
        {
            if ($taskProgress->needThatToProgress > $taskProgress->alsoNeeded)
            {
                $taskProgress->needThatToProgress = 0;
            }

        }
    }
}





Aucun commentaire:

Enregistrer un commentaire