Symfony config component and service for Doctrine DBAL

烈酒焚心 提交于 2019-12-13 06:55:52

问题


This is a continuation of Symfony config component and Doctrine dbal

I am trying to create service for doctrine now like this:

<?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);
    }
}

And then i am trying to call it like

$doctrineConnection = $sysContainer->get('doctrine');

$sqlQuery = 'SELECT * FROM `thoughts`';
$queryResult = $doctrineConnection->query($sqlQuery)->fetch();

But i am getting error

Fatal error: Call to undefined method Localhost\Service\Doctrine::query() 

Why, without service it's working perfectly? p.s. If you have better ideas or advices how to rewrite this code to fit symfony service structure, i would be happy to hear them.


回答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);
    }
}

Then in services.yml file:

doctrine:
    class: Doctrine\DBAL\Connection
    factory_class:  'Localhost\Service\Doctrine'
    factory_method: 'create'


来源:https://stackoverflow.com/questions/22426444/symfony-config-component-and-service-for-doctrine-dbal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!