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.
custom classis a service? - Victor Bocharskyarguments: [@database_connection]. This is a solution what you need. So use$this->connectionin this service - Victor Bocharsky