I followed this SO answer to build my DBAL connection as service.
I have the following configuration:
In my service class file "Doctrine.php", I have
<?php
namespace Acme\BookBundle\Services;
use Doctrine\Common\ClassLoader;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;
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' => 'book_enterprise_hub',
'host' => 'localhost',
'user' => 'root',
'password' => '',
];
return DriverManager::getConnection($doctrineParams, $doctrineConfig);
}
}
?>
In my services.yml, I have the following:
parameters:
dbal_connection: book_enterprise_hub
services:
doctrine:
class: Doctrine\DBAL\Connection
factory_class: 'Acme\BookBundle\Services\Doctrine'
factory_method: 'create'
In my CompanyController.php, I have the following code,
<?php
use Acme\BookBundle\Services\Doctrine;
class CompanyController extends Controller
{
public function createAction()
{
$con = $this->get('doctrine');
$sqlQuery = "CREATE TABLE book_info (id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, label TEXT, created_on DATETIME) ENGINE = INNODB";
$stmt = $con->prepare($sqlQuery);
$stmt->execute();
}
}
When calling this line $con->prepare($sqlQuery),
I get the following error,
Attempted to call method "prepare" on class "Doctrine\Bundle\DoctrineBundle\Registry" in C:\wamp\www\symfony\src\Acme\BookBundle\Controller\CompanyController.php
Actually, I am using factory method for getting DBAL connection as service but kept getting this error. Can I write parameters in service.yml as given above or I should write in parameters.yml only? What am I doing wrong?