phpsymfonydoctrinesymfony-2.8pdo-odbc

Use Symfony2 with PDO_odbc and use services and repositories for connection and queries


For my company I'm working on a Symfony webapp that needs to fetch users and businesses from the database. However I am forced to use an ODBC connection. I went with pdo_odbc and this is working fine from the controller (Connection, queries, fetching, rendering).

But I'm a bit lost on how to use Entities and Repositories if I'm unable to use Doctrine to connect.

So what I'm doing now is connecting to the database, do queries, fetching data and rendering to the views in one controller function. Without using Entities or Repositories, this is obviously not what it should be.

If any of you need more information feel free to comment.

PS: I'm new to Symfony in general, so examples are much appreciated


Solution

  • We're doing the same stuff on some projects.

    We've done the following steps:

    The repositories we've written just are classes that are defined as services and will receive the doctrine connection as constructor injection. Then you can get the connection and work with PDO.

    Example for a repository class (note that we just call them repositories because they handle the database queries, but they have nothing to do with the Repository classes from Symfony / Doctrine)

    class DemoRepositoryClass
    {
        private $connection;
    
        public function __construct(Registry $doctrine)
        {
            // Get the database connection from doctrine
            $this->connection = $doctrine->getConnection();
        }
    
        public function test()
        {
            $query = "SELECT * FROM XXX WHERE FOO = 'BAZ";
            $stmt = $this->conncetion->prepare($query);
            // [...] Do as always with PDO;
        }
    
    }
    

    This class will be defined as service in the services.yml

    app.demo_repository_class:
        class: AppBundle\Path\DemoRepositoryClass
        arguments: ['@doctrine']
        public: true
    

    With that, you can call the service functions from the controller as example:

    // In a controller action/function
    $this->get('app.demo_repository_class')->test();