DBAL connection as service throws error

webblover

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?

webblover

Finally I read service container very carefully in symfony doc and utilzed an answer given by someone in a different post and got the following config to work for me:

In my services.yml,

parameters:
    dbal_connection: book_enterprise_hub
    bookservice.class:   Acme\BookBundle\Services\BookService

services:
    bookservice:
        class:      %bookservice.class%

** Note, I am not passing arguments here, because when passed, it threw this error "You have requested a non-existent service "doctrine.dbal.book_enterprise_hub", so, I pass this DB information in bookservice __construct method.".

In my service file BookService.php,

<?php
namespace Acme\BookBundle\Services;

//1st method (not working)
//use Doctrine\DBAL\Connection;

//second method
use Doctrine\Common\ClassLoader;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;

class BookService
{
    private $connection;

    //1st method (not working)
    // public function __construct(Connection $connection)  {
    //     $this->connection = $connection;
    // }


    //second method
    public function __construct()  {
        $doctrineLoader = new ClassLoader('BookService');
        $doctrineLoader->register();

        $doctrineConfig = new Configuration();
        $doctrineParams = array(
            'driver' => 'pdo_mysql',
            'dbname' => 'book_enterprise_hub',
            'host' => 'localhost',
            'user' => 'root',
            'password' => '',
        );
        $this->connection = DriverManager::getConnection($doctrineParams, $doctrineConfig);
    }


    public function createTable($tableName){

        $sqlQuery = "CREATE TABLE ".$tableName." (id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, label TEXT, created_on DATETIME) ENGINE = INNODB";
        $stmt = $this->connection->prepare($sqlQuery);
        if($stmt->execute())
        {
            return true;
        }
    }
}

In my BookController.php, I could access the DBAL as service like this,

<?php
use Acme\BookBundle\Services\BookService;

class BookController extends Controller
{
    /**
     * Creates a new Book entity.
     *
     */
    public function createAction()
    {
        $tableName = $form->get('entityId')->getData();
        $obj = $this->get('bookservice');
        if($obj->createTable($tableName) == true){
            // some code.
        }
    }
}   

With this config, "You have requested a non-existent service. 500 Internal Server Error - ServiceNotFoundException" is resolved.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Starting created service using sc.exe throws error: "[SC] StartService FAILED with error 129."

分類Dev

react-native run-android command throws "java.net.ConnectException: Connection timed out" error

分類Dev

MySQL connection throws null reference

分類Dev

Nssm service throws errors on startup

分類Dev

Kubernetes MLflow Service Pod Connection

分類Dev

SQL insert query throws error

分類Dev

Closing a form on initialize throws error

分類Dev

Java : Parsing Long throws error

分類Dev

Why assert throws a reference error

分類Dev

Laravel Connection Refused Error

分類Dev

Error in establishing websocket connection

分類Dev

Yii DB Connection Error

分類Dev

ssrs DB connection error

分類Dev

MySQL and php connection error

分類Dev

SQL Connection Error Message

分類Dev

ActiveMQ http connection error

分類Dev

HikariCP connection error

分類Dev

Failed to initiate service connection to simulator Xcode

分類Dev

Retrieve Service Bus event hub connection string

分類Dev

TTS leaked service connection that was orignially bound here

分類Dev

Will Azure Service Bus connection survive Azure Service Fabric node shuffling?

分類Dev

Adding a repository throws bean creation error

分類Dev

.MySQL throws an error in a JDBC Prepared statement?

分類Dev

remove method throws error in List interface iterator

分類Dev

Node.js throws "btoa is not defined" error

分類Dev

Bash if statement with multiple conditions throws an error

分類Dev

PHPUnit mock throws incompatible declaration error

分類Dev

NPM throws error "couldn't read dependencies"?

分類Dev

My scraper throws an error instead of continuing on

Related 関連記事

ホットタグ

アーカイブ