2
votes

In the process of writing a symfony2 application, I need to write a custom model layer for all the database interactions, and I'd like to use Doctrine DBAL, not the full ORM. This because I didn't design the database and a set of predefined queries must be used.

I get that I can just call a service for the DBAL connection from the controller, like:

$results = $this->get('my_service')->someMethod();

having defined the service as:

src/Acme/BundleName/Resources/config/services.yml

services:
  my_service:
  class:  Acme\BundleName\Entity\BaseEntity
  arguments:  [@database_connection]

src/Acme/BundleName/Entity/BaseEntity.php

namespace Acme\BundleName\Entity;
use Doctrine\DBAL\Connection;

class BaseEntity
{
  private $connection;

  public function __construct(Connection $dbalConnection)  {
      $this->connection = $dbalConnection;    
 }

 public function someMethod(){
   //method logic
 }

}

Now, how can I call that service from my custom model class, so I can use the dbal connection for executing raw slq?

I also get that I could define every class as a service that would have the dbal connection injected, but this would lead me to have dozens of defined services (one for each model class) only for sharing the dbal connection.

Ideally I would like to have my classes mapping the database tables, with custom logic, like many other frameworks do. I also know that I can define custom "Repository" in Doctrine orm, but I need to stick with only the DBAL layer.

1
You can use and DBAL and Doctrine repositories in Symfony, so what is your question? - Victor Bocharsky
How can I get a DBAL connection from a custom class (my model classes)? - Carlo
You mean custom class is a service? - Victor Bocharsky
I actually don't know if it should be a service or not, I am looking for a way to have the DBAL connection in my custom model classes and I thought defining it into a service was a good approach, but I can get that service (the dbal connection service) only from a Controller class. - Carlo
But you already inject DBAL to service with arguments: [@database_connection]. This is a solution what you need. So use $this->connection in this service - Victor Bocharsky

1 Answers

0
votes

So, I think You need to create a service, inject in it Doctrine DBAL dependency, and load and work with your models via this service

public function someMethod(){
   //load the model
   $model = new MyModel();
   // Then get data from DB and fetch them to model

   //other method logic
   return $model;
}