php – symfony2 – 在存储库或类中使用多个连接
发布时间:2020-12-13 16:35:45 所属栏目:PHP教程 来源:网络整理
导读:我有多个连接,我有一个存储库类.我希望存储库类可以访问多个连接.它用于需要从多个数据库主机获取数据的报告. config.yml doctrine: dbal: default_connection: default connections: default: driver: "%db_default_driver%" host: "%db_default_host%" etc
我有多个连接,我有一个存储库类.我希望存储库类可以访问多个连接.它用于需要从多个数据库主机获取数据的报告.
config.yml doctrine: dbal: default_connection: default connections: default: driver: "%db_default_driver%" host: "%db_default_host%" etc.. bookings: driver: "%db_readonly_bookings_driver%" host: "%db_readonly_bookings_host%" etc ... sessions: etc.. SalesJournalRepistory.php namespace PortalSalesJournalBundleRepository; use DoctrineORMEntityRepository; class SalesJournalRepository extends EntityRepository { public $connDefault = null; public $connBookings = null; public $connSessions = null; function __construct() { // this is where I get the error $this->connDefault = $this->getManager('default')->getConnection(); $this->connBookings = $this->getManager('bookings')->getConnection(); $this->connSessions = $this->getManager('sessions')->getConnection(); } function testQuery(){ $sql = "SELECT * FROM testTableBookings LIMIT 10"; $stmt = $this->connBookings->prepare($sql); $results = $stmt->fetchAll(); print_r($results); } function testQuery2(){ $sql = "SELECT * FROM testTableSessions LIMIT 10"; $stmt = $this->connSessions->prepare($sql); $results = $stmt->fetchAll(); print_r($results); } } 我可以让它从一个控制器工作 $connDefault = $this->getDoctrine()->getManager('default')->getConnection(); $connBookings = $this->getDoctrine()->getManager('bookings')->getConnection(); 然而,我希望能够从存储库运行它.我得到以下错误 PHP Fatal error: Call to a member function getConnection() on a non-object 我以为这可能会提供一些线索? enjecting entities但是我有点困惑,不知道是不是?
EntityRepository只应该关注其拥有的实体(和管理者) – 所以将实体存储库与实体管理器混合是非常方便的.我建议你创建一个服务并注入原则 – 然后你可以查询任何你想要的.例如 :
配置 [config.yml / services.yml] services: sales_journal: class: AcmeDemoBundleServiceSalesJournal arguments: ['@doctrine'] 服务 [AcmeDemoBundleServiceSalesJournal.php] namespace AcmeDemoBundleService; public class SalesJournal { private $connDefault; private $connBookings; private $connSessions; function __construct($doctrine) { $this->connDefault = $doctrine->getManager('default')->getConnection(); $this->connBookings = $doctrine->getManager('bookings')->getConnection(); $this->connSessions = $doctrine->getManager('sessions')->getConnection(); } function testQuery() { $sql = "SELECT * FROM testTableBookings LIMIT 10"; $stmt = $this->connBookings->prepare($sql); $results = $stmt->fetchAll(); print_r($results); } function testQuery2() { $sql = "SELECT * FROM testTableSessions LIMIT 10"; $stmt = $this->connSessions->prepare($sql); $results = $stmt->fetchAll(); print_r($results); } } 然后从您的控制器或您想要使用您可以做的服务: // get the service $sales_journal = $this->get('sales_journal'); // call relevent function $sales_journal->testQuery(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |