duanfei8149
duanfei8149
2014-04-27 15:58

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.

services.yml

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

CompanyService.php

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;
    }
}

config.yml

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 dsyrdwdbo47282676 7年前

    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.

    点赞 评论 复制链接分享