这是Symfony config component and Doctrine dbal
的延续我正在尝试为这样的教义创建服务:
<?php
namespace Localhost\Service;
use Doctrine\Common\ClassLoader;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;
class Doctrine
{
public function __construct()
{
$doctrineLoader = new ClassLoader('Doctrine');
$doctrineLoader->register();
$doctrineConfig = new Configuration();
$doctrineParams = [
'driver' => 'pdo_mysql',
'dbname' => 'levelup',
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'toor',
];
return DriverManager::getConnection($doctrineParams, $doctrineConfig);
}
}
然后我试着把它称为
$doctrineConnection = $sysContainer->get('doctrine');
$sqlQuery = 'SELECT * FROM `thoughts`';
$queryResult = $doctrineConnection->query($sqlQuery)->fetch();
但我收到错误
Fatal error: Call to undefined method Localhost\Service\Doctrine::query()
为什么,没有服务,它的工作完美? 附:如果您有更好的想法或建议如何重写此代码以适应symfony服务结构,我很乐意听到它们。
答案 0 :(得分:1)
class Doctrine
{
// Just rename __construct to create and make it static
static function create()
{
$doctrineLoader = new ClassLoader('Doctrine');
$doctrineLoader->register();
$doctrineConfig = new Configuration();
$doctrineParams = [
'driver' => 'pdo_mysql',
'dbname' => 'levelup',
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'toor',
];
return DriverManager::getConnection($doctrineParams, $doctrineConfig);
}
}
然后在services.yml文件中:
doctrine:
class: Doctrine\DBAL\Connection
factory_class: 'Localhost\Service\Doctrine'
factory_method: 'create'