我正在尝试改善我的PHP-DI配置,现在我卡住了。
我想将已经定义的类重用于另一个类。
entityManager
类应来自Database->getEntityManager
这是我的di配置文件的一部分:
return [
'database.user' => 'xxxxxxx',
'database.password' => 'xxxxxxx',
'database.name' => 'xxxxxxx',
'database.host' => '127.0.0.1',
'database.port' => 3306,
\ABCData\Database\Database::class => DI\autowire()->constructor(
DI\get('database.user'),
DI\get('database.password'),
DI\get('database.name'),
DI\get('database.host'),
DI\get('database.port')
),
// \Doctrine\ORM\EntityManager::class => DI\factory(function () {
// $database = new ABCData\Database\Database(
// \ABCData\Database\Config::DB_USER,
// \ABCData\Database\Config::DB_PASSWORD,
// \ABCData\Database\Config::DB_DATABASE,
// \ABCData\Database\Config::DB_HOST
// );
// return $database->getEntityManager();
// }),
\Doctrine\ORM\EntityManager::class => DI\autowire(\ABCData\Database\Database::class)->method('getEntityManager'),
...
当我注入数据库时,这很好。注释过的定义很好用,但我想达到的是最后一行,但失败了。
这是我对数据库类的完整实现:
private $userName;
private $password;
private $database;
private $host;
private $port;
public function __construct($username, $password, $database, $host, $port = 3306)
{
$this->userName = $username;
$this->password = $password;
$this->database = $database;
$this->host = $host;
$this->port = $port;
}
public function getEntityManager()
{
$isDevMode = true;
$paths = [APP_DIR . 'classes/Entities'];
$connectionCredentials = $this->getConnectionCredentials();
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$entityManager = \Doctrine\ORM\EntityManager::create($connectionCredentials, $config);
$connection = $entityManager->getConnection();
$sqlSchemaManager = new SQLServerSchemaManager($connection);
$sqlSchemaManager->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
return $entityManager;
}
private function getConnectionCredentials()
{
return [
'driver' => 'pdo_mysql',
'user' => $this->userName,
'password' => $this->password,
'dbname' => $this->database,
'host' => $this->host,
'port' => $this->port
];
}
当我的代码需要实例化entityManager
时,出现此错误:
Entry "ABCData\ABCDataAPI\CronJob" cannot be resolved: Entry "ABCData\DataStructure\Save" cannot be resolved: Entry "Doctrine\ORM\EntityManager" cannot be resolved: Parameter $username of __construct() has no value defined or guessable
Full definition:
Object (
class = ABCData\Database\Database
lazy = false
__construct(
$username = #UNDEFINED#
$password = #UNDEFINED#
$database = #UNDEFINED#
$host = #UNDEFINED#
$port = (default value) 3306
)
getEntityManager(
)
)
似乎没有使用先前定义的数据库对象。
我怎么了?
答案 0 :(得分:0)
好的,我误解了文档。
这就是我所做的。如果您有更好的主意,请告诉我:
\Doctrine\ORM\EntityManager::class => DI\factory(function (\ABCData\Database\Database $database) {
return $database->getEntityManager();
}),