One library depends on another - what's the solution? |
Hello,
To make sure I use the proper practice, I have to fully explain what's going on. I have a library called 'Ui', responsible for displaying the front end. (It displays a main view that has other views inside it, variables for each view, and so on.) The object for this library is created in BaseController::initController(). So all controllers have access to the $this->ui object. I suppose this is fine so far. I have another library however, called 'Auth', which is responsible for handling the user logged in. Both classes are autoloaded like this: PHP Code: public $classmap = [ The constructor of Auth has to set a variable for Ui, which means Ui depends on Auth*. The two libraries have no access to one another though. * EDIT: Auth depends on Ui This same method worked fine in CI 2-3, where Auth simply executed a $this->ui->... method. Is there a simple solution for this, or is the whole concept wrong? Should I use libraries for both these things in the first place? Thanks for your time.
Use services for dependency injection.
https://codeigniter.com/user_guide/conce...vices.html (07-28-2022, 12:06 PM)leafface Wrote: The constructor of Auth has to set a variable for Ui, which means Ui depends on Auth. The two libraries have no access to one another though. It seems your explanation is something wrong. If the constructor of Auth has to set a variable for Ui, that is Auth depends on Ui. I think something like this: PHP Code: class Auth { If the two libraries really have no access to one another though, you don't need to set a variable for Ui in the Auth constructor. But you say "Auth simply executed a $this->ui->... method". That is Auth has access to Ui. (07-28-2022, 07:47 PM)iRedds Wrote: Use services for dependency injection. The thing why I decided against solving this with services is that the user guide says: "It is recommended to only create services within controllers." My Ui library is used outside of controllers as well, e.g. in the Auth library.
Your solution works! Many thanks!
BTW: Yes, sorry, Auth depends on Ui, not the other way around. |
Welcome Guest, Not a member yet? Register Sign In |