samedi 7 janvier 2017

PHP - Service layer class instantiation causing infinite loop

I have service layer classes which performs the business logic.

I have a class say UserService which performs user role related service like checking if user is admin, user has access to project, user has particular role or not, etc. And there is a another class say ProjectService which deals with project related things like getting project members, project details, etc.

UserService 
   $projectService;  //class variable

   hasProjectAccess(){
   {
     ...
     projectMember = projectService->getProjectMembers();
     ...
   }

   isUserAdmin(){
       return true|false; //just an example
   }

ProjectService 
   $userService;    //class variable
   getProjectMembers(){
   {
     ...
     perform some logic to create array of members
     ...
     if(userService.isUserAdmin())
        .. perform some other logic
     ...
   }

I am using Slim 3, where I use it Container class to instantiate and inject all dependencies.

Now when I try to instantiate UserService class I have to instantiate the ProjectService class inside it (using setters method), which in turn has to instantiate UserService class .... and so on... which creates an infinite loop (cyclic dependency).

I am trying to achieve something like in Java/Spring, where you have different services which you need in your class and they wired into it using Spring so you do not have to worry about the cyclic dependency.

Let me know if more information is needed.

Aucun commentaire:

Enregistrer un commentaire