1

I'm trying to use ray di to inject data in the constructor. But I am having some problem. Here is my code

<?php

declare(strict_types=1);

namespace App\action;

require __DIR__ . '../../../vendor/autoload.php';

use Ray\Di\AbstractModule;
use Ray\Di\Injector;


interface DbInterface
{
}

class Db implements DbInterface
{
    private $dsn;
    private $username;
    private $password;

    public function __construct($dsn,$username,$password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
    }

}

class PostgreDb implements DbInterface
{
    private $dsn;
    private $username;
    private $password;

    public function __construct($dsn,$username,$password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
    }

}

class FinderModule extends AbstractModule
{
    protected function configure()
    {

        $this->bind(Db::class)->toConstructor(Db::class, ['dsn'=>'dsn','username'=>'username','password'=>'password']);
        $this->bind(PostgreDb::class)->toConstructor(PostgreDb::class, ['dsn'=>'dsn','username'=>'username','password'=>'password']);

        $this->bind()->annotatedWith('dsn')->toInstance('msql:host=localhost;dbname=test');
        $this->bind()->annotatedWith('username')->toInstance('root');
        $this->bind()->annotatedWith('password')->toInstance('52');

    }
}
$dbName = PostgreDb::class;
$injector = new Injector(new FinderModule);
$temp = $injector->getInstance($dbName);
print_r( $temp );

Now I am using two classes Db & PostgreDb. Later I am planning to use new classes like MysqlDb, SqliteDb etc. And I don't want to change configure() every time I create a new class.

Can anyone help me? Thanks.

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
John
  • 21
  • 3

0 Answers0