php - 使用 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()
每次创建新类时都改变。
谁能帮我?谢谢。
解决方案
推荐阅读
- arduino - ESP32(Arduino Core):设置函数中的“while(true)”循环
- python - 为什么我得到这个输出
- typescript - Typescipt - 交叉点类型 - 唯一符号
- javascript - 如何更改 Javascript 中关键帧的 CSS 属性?
- node.js - 如何在本地计算机上运行 Node.js 应用程序并使用 No-IP 让其他人从 Internet 访问它?
- python - Django:如何从 excel 中的用户表授予用户帐户
- binding - 如何在 SwiftUI 中控制 AVPlayer?
- c - 如何将路径传递给我的功能以将目录的文件复制到另一个目录
- cmake - 在库依赖项中为多个目标定义编译定义
- c++ - 映射内的向量迭代器(字符串)