首页 > 解决方案 > 使用 Ray Di 在构造函数中动态注入数据

问题描述

我正在尝试使用ray di在构造函数中注入数据。但我遇到了一些问题。这是我的代码

<?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 );

现在我正在使用两个类Db& PostgreDb。后来我打算使用新的类MysqlDb,比如SqliteDb等。我不想configure()每次创建新类时都改变。

谁能帮我?谢谢。

标签: phpdependency-injectionphp-di

解决方案


推荐阅读