我正在尝试使用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()
每次创建新类时都改变。
谁能帮我?谢谢。