Conflict IoC Laravel 5.3

1

I have the following codes:

Chat Staff Service

namespace Chat\Api\V1\Services\Chat;

class ChatStaffService extends Service
{

     private $chatService;

     public function __construct(ChatService $chatService)
     {
         $this->chatService = $chatService;
     }

     ...
}

Chat Service

namespace Chat\Api\V1\Services\Chat;

class ChatService extends Service
{
     private $chatStaffService;

     public function __construct(ChatStaffService $chatStaffService)
     {

         $this->chatStaffService = $chatStaffService;
     }

     ...
}

What's happening: In developing an API at some point I use ChatStaffService functions in ChatService and at other times I need to use ChatService functions in ChatStaffService. When I put dependency on any of the constructors the application simply stops and returns error 500. When I remove the dependency and try to use a function that does not need it everything returns to normal operation.

I need some idea to get around this problem. I tried to develop the following function to solve the problem but it did not work.

     function checkAndInject($anInstance, $injection)
     {
         if($anInstance == true)
            return $injection;
         else
            return \App::make($injection);
     }
    
asked by anonymous 13.01.2017 / 14:58

1 answer

0

The problem lies in the design of your classes. It is simply impossible to instantiate any of the classes because one depends on the other. If I were to build them manually, what would it be like?

$chat = new ChatService(new ChatStaffService(new ChatService(...)));

This is exactly what Laravel does, tending to infinity, until PHP breaks.

And what can you do in this case? Rethink the structure of your classes. The ChatStaffService class seems to me to be a specialization of ChatService , so implement more generally the ChatService class, so that it does not depend on anything with ChatStaffService .

ChatStaffService can be a simple inheritance of ChatService , so it can use the methods of ChatService and if it does something different, it just overwrites the method.

With this you do not need to inject anything into the constructor.

// ChatService    
namespace Chat\Api\V1\Services\Chat;

class ChatService extends Service
{
     private $chatStaffService;

     public function __construct()
     {

         //
     }

}

// ChatStaffService
namespace Chat\Api\V1\Services\Chat;

class ChatStaffService extends ChatService
{
     public function __construct()
     {
         //
     }

}
    
19.01.2017 / 02:16