0

I know this is kind of a sin, but I don't have any code to show, it is just that I completely hit a brick wall. My problem is the following.

I have a client that connects to a Lumen/Dingo Api. For all the requests it works great. For example:

My route:

$api->get('contact', 'ContactController@get');

Coupled with this I have a ContactController and inside I have a get function that returns a response. No problem here.

Now the following problem:

I have a route with tasks:

$api->get('task/{id}', 'TaskController@get');

The problem is that in the system not all the Tasks are the same. Depending on the Type of task I want to perform special actions. I was thinking of creating a new Controller for each Task. Like MySpecialTask1Controller, MySpecialTask2Controller and from my main TaskController I redirect to another controller.

Problem is 1) I do not know how to do this, and 2) I do not know if this would be the best way to do this.

Maybe this problem can be solved with services or other tools Dingo/Lumen provide. Maybe someone can help me out on this.

José Ricardo Pla
  • 1,043
  • 10
  • 16
Saif Bechan
  • 16,551
  • 23
  • 83
  • 125

1 Answers1

0

I wouldn't bother with controller for each task, I would rather go for a service class that handles that and is called in the TaskController.

The service class would have a public handle() method (or find a better name for it) which will take 1 argument (based on what you described). The parameter will be the type of task you need to do.

I would have another protected method which will have a lookup table based on the type you provide, it will call the corresponding class and execute the method within that class.

This is also called polymorphism.

Code example:

class TaskController extends Controller 
{
    protected $taskService;

    public __construct(TaskService $taskService)
    {
        $this->taskService = $taskService; 
    }

    public function someMethod()
    {
        // determine the type of task and then
        $this->taskService->handle($type)
    }
}

class TaskService 
{
    public function handle($type)
    {
        $this->doTask($type);
    }

    protected function doTask($type) 
    {
        // the lookup table
        $tasks = [
           'crazy' => new CrazyTask(),
           'insane' => new InsaneTask(),
           'hard' => new HardTask(), 
           'easy' => new EasyTasK()
       ];

       foreach($tasks as $taskType => $task)
       {
           if($taskType === $type) {
              return $task->do();
           }

       }
    }
}

This code should give you an idea how you can solve your problem using this design pattern (I can't think of the name right now).

Davor Minchorov
  • 2,018
  • 1
  • 16
  • 20