duanfei8149 2014-04-27 15:58
浏览 93
已采纳

Symfony2中的多个数据库

I have an application with two database connections. First database is application's own database and second database is from another application (same server, different subdomain).

For SQL queries on the second database I use services.

<kbd>services.yml</kbd>

login.company:
    class: JP\CoreBundle\Service\Login\CompanyService
    arguments:
        em: "@doctrine.orm.login_entity_manager"

<kbd>CompanyService.php</kbd>

class CompanyService {    
    private $_em;

    public function __construct(EntityManager $em){
        $this->_em = $em;
    }

    public function getSomethingBySomething($something){ // Intentionally obscured method and parameter name
        $conn = $this->_em->getConnection();

        $sql = ''; // Intentionally removed SQL query

        $stmt = $conn->prepare($sql);
        $stmt->bindParam('something', $something); // Intentionally obscured real name to something
        $stmt->execute();

        return ($stmt->rowCount() == 1) ? $stmt->fetch(Query::HYDRATE_ARRAY) : false;
    }
}

<kbd>config.yml</kbd>

doctrine:
    dbal:
        default_connection: analysis
        connections:
            analysis:
                driver:   "%database_driver1%"
                host:     "%database_host1%"
                port:     "%database_port1%"
                dbname:   "%database_name1%"
                user:     "%database_user1%"
                password: "%database_password1%"
                charset:  UTF8
            login:
                driver:   "%database_driver2%"
                host:     "%database_host2%"
                port:     "%database_port2%"
                dbname:   "%database_name2%"
                user:     "%database_user2%"
                password: "%database_password2%"
                charset:  UTF8
    orm:
        default_entity_manager: analysis
        entity_managers:
            analysis:
                connection: analysis
                mappings:
                    JPCoreBundle: ~
            login:
                connection: login
        auto_generate_proxy_classes: "%kernel.debug%"

Question: Is this correct use of multiple databases in Symfony2 environment? Could it be improved somehow?

  • 写回答

1条回答 默认 最新

  • dsyrdwdbo47282676 2014-04-30 21:08
    关注

    Is this correct use of multiple databases in Symfony2 environment?

    This is the correct use of multiple databases in Symfony2.

    Could it be improved somehow?

    The only improvement (as mentioned in comments) which is not directly related to use of multiple database in Symfony2 is to use DQL or QueryBuilder instead of using the connection directly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?