Welcome Guest, Not a member yet? Register   Sign In
One library depends on another - what's the solution?
#1

(This post was last modified: 07-29-2022, 04:12 AM by leafface.)

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 = [
  'Ui' => APPPATH.'/Libraries/Ui.php',
  'Auth' => APPPATH.'/Libraries/Auth.php',
]; 

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.
Reply
#2

(This post was last modified: 07-28-2022, 07:49 PM by iRedds.)

Use services for dependency injection.
https://codeigniter.com/user_guide/conce...vices.html
Reply
#3

(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.

This same method worked fine in CI 2-3, where Auth simply executed a $this->ui->... method.

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 {
    private $ui;
    public function __construct($ui) {
        $this->ui $ui;
    }


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.
Reply
#4

(This post was last modified: 07-29-2022, 02:13 AM by leafface.)

(07-28-2022, 07:47 PM)iRedds Wrote: Use services for dependency injection.
https://codeigniter.com/user_guide/conce...vices.html

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.
Reply
#5

Your solution works! Many thanks!

BTW: Yes, sorry, Auth depends on Ui, not the other way around.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB