Injecting dependencies through the constructor

I’m not sure how to inject dependencies through the constructor.
(I’m getting the notice on this ‘issue’ otherwise i wouldn’t even be aware of this:
Static access increases dependencies and leads to hard to test code. You should instead inject dependencies through the constructor)

let’s a ssume there’s a class with a static method, eg

class MySimpleClass
{
    public static function foo($name, $number)
    {
        // ...
    }
}

this function will be calles in another class, eg

class MyMainClass
{
    public function bar($name, $number)
    {
        // ...
        MySimpleClass::foo($name, $number);
    }
}

Can anybody help me solving this by using the constructor

There are two issues here, one is the use of static methods, which usually are equivalent to global variables. (e.g. in your second code, try to write a unit test that is not depending on MySimpleClass)

the second one is the dependency injection itself. best explained with an example:

class MyClass
{
    private $db;

    public function __construct(PDO $db)
    {
        $this->db = $db;
    }

    // ...
}
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$obj = new MyClass($pdo);
$obj->doSomething();

here you pass a PDO instance (database connection), to the MyClass object so you can query the database from within the MyClass instance.

1 Like

@Dormilich thanks for the answer but it doesn’t bring me much further.
I know the very basics abou injection (as you provided in the example), but i’m stuck with the piece of code i’m working on, on how to modify it. That’s still beyond my scope.

you would have to completely rewrite your code. Dependency Injection makes no sense with static methods.

You better post a real life (though simplified!) example, as it’s hard to offer anything for such an artificial sketch.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.