0

这是Symfony 配置组件和 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() 

为什么,没有服务,它工作得很好?ps 如果您有更好的想法或建议如何重写此代码以适应 symfony 服务结构,我会很高兴听到它们。

4

1 回答 1

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'
于 2014-03-15T17:44:38.877 回答