Search code examples
phpdesign-patternsdatamapper

PHP using multiple MySQL database connections


I'm creating an application that makes use of 3 different databases on different servers. Fetching data happens in my Data mappers, each extending an abstract DataMapper parent class:

abstract class DataMapper {

    protected $db;
    protected $db2;
    protected $db3;

    function __construct() {
        $this->db = new Database('db1');
        $this->db2 = new Database('db2');
        $this->db3 = new Database('db3');
    }

}

However, this would be a little overkill for pages that only requires one of these 3 connections. What would be the best way to return the correct Database connection for every part of the application? I've heard about Application Registries, but I have no idea how to set up something like that.


Solution

  • I don't like how you're setting up your data mappers. You're creating a new connection for every mapper, even if it uses a provider that already has an established connection. In other words, every data mapper creates a new database object.

    Ideally, these database objects should be saved and passed to the data mappers that need them. Auto injecting typically works pretty well. What that means is you don't have to instantiate objects with the new keyword, but by requesting them through your object's constructing paramters.

    For example:

    class Example1Mapper extends DataMapper {
        function __construct( Provider1 $provider1 ) { ... }
    }
    
    class Example2Mapper extends DataMapper {
        function __construct( Provider1 $provider1, Provider2 $provider2 ) { ... }
    }
    

    Above, two mapper classes need different providers. The only thing you need to do is specify this through the object's constructor. Automatic dependency injecting/autowiring does the rest.

    I don't know how your architecture is established, but this is what I do: the router and injector work together. The router determines what controller should be called and what action (method) should be called. The injector takes this information and reflects the controller's parameters. It also reflects the paramters' paramaters, and so on... The injector creates all the objects and decides what db providers, domain objects, etc... to pass. Here and here would be good places to begin learning on injectors, but you probably want to do some reading around. There are also a few good lightweight DICs.