Php 用于DBAL的Symfony配置组件和服务

Php 用于DBAL的Symfony配置组件和服务,php,doctrine-orm,symfony-components,Php,Doctrine Orm,Symfony Components,这是本书的延续 我现在正试图为条令创建如下服务: <?php namespace Localhost\Service; use Doctrine\Common\ClassLoader; use Doctrine\DBAL\Configuration; use Doctrine\DBAL\DriverManager; class Doctrine { public function __construct() { $doctrineLoader = ne

这是本书的延续

我现在正试图为条令创建如下服务:

<?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);
    }
}
但我犯了一个错误

Fatal error: Call to undefined method Localhost\Service\Doctrine::query() 
为什么,没有服务它工作得很好? p、 如果您有更好的想法或建议如何重写此代码以适应symfony服务结构,我将很高兴听到他们

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'

__构造永远不会返回任何内容,因此尝试让它返回连接对象将不起作用。你想建一个工厂。您想用静态方法Doctrine::create()替换_构造。然后看这里:看看如何使用工厂。@Cerad,谢谢你的帮助,你能详细描述一下你的
意思吗?你想用静态方法Doctrine::create()替换uu构造。
非常感谢你,非常有魅力,现在我有一个材料要学习!
doctrine:
    class: Doctrine\DBAL\Connection
    factory_class:  'Localhost\Service\Doctrine'
    factory_method: 'create'