问题
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