我正在使用DBAL與Doctrine在Symfony 3中建立連接到數據庫。我想要做的是將所有查詢都放在PHP文件中,而不是放在控制器中。如何連接到一個PHP文件中的多個數據庫?
在控制器我可以用這個:
$conn = $this->get('doctrine.dbal.database2_connection');
獲得一個連接,但在一個簡單的PHP我不能。
所以,我不知道如何在不使用EntityManager
對象的情況下調用多個連接,因爲我沒有使用實體類。
我正在使用DBAL與Doctrine在Symfony 3中建立連接到數據庫。我想要做的是將所有查詢都放在PHP文件中,而不是放在控制器中。如何連接到一個PHP文件中的多個數據庫?
在控制器我可以用這個:
$conn = $this->get('doctrine.dbal.database2_connection');
獲得一個連接,但在一個簡單的PHP我不能。
所以,我不知道如何在不使用EntityManager
對象的情況下調用多個連接,因爲我沒有使用實體類。
如果您使用PDO,則每個連接都被視爲一個對象,並且您可以同時擁有任意數量的連接。 Check out the docs
要達到你要需要掌握接下來的事情就什麼:
你需要檢查如何與多個數據庫工作(我想這是你的許多連接的意思)in the documentation。
此外,您還需要了解如何create custom repositories.
您將需要使用DQL (doctrine query language)做自己的查詢。
而最後一點是,你需要Symfony's dependency injection.
所用得到隨意跳過你已經知道了一切。我不能在這裏詳細說明一切,因爲你的問題很模糊。所以這個答案將指導你如何找到你的解決方案或者至少關注你的問題。
Symfony允許您連接多個數據庫。你需要做一個BT鍛鍊來達到這個目標。
第1步
添加參數parameters.yml
文件。第二數據庫連接可以使用以下參數被添加:
Parameters:
# First database
database_host: 127.0.0.1
database_port: null
database_name: qmsfumgabd
database_user: qmsfumgabd
database_password: xxx9bxxMxx
# Second database
database2_host: 127.0.0.1
database2_port: null
database2_name: huscqxzwaw
database2_user: huscqxzwaw
database2_password: dxxxFXxxxB
步驟#2
下一步是獲得在config.yml
這些憑證:
doctrine:
# Configure the abstraction layer
dbal:
# Set the default connection to default
default_connection: default
connections:
default:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
database2:
driver: pdo_mysql
host: '%database2_host%'
port: '%database2_port%'
dbname: '%database2_name%'
user: '%database2_user%'
password: '%database2_password%'
charset: UTF8
步驟#3
最後,指定項目中每個包的映射:
# Configure the ORM
orm:
default_entity_manager: default
entity_managers:
# Register which bundle should use which connection
default:
connection: default
mappings:
AppBundle: ~
DemoBundle: ~
database2:
connection: database2
mappings:
CloudwaysBundle: ~
步驟#4
現在對於調用任何簡單的實體管理器使用連接名稱:
class UserController extends Controller
{
public function indexAction()
{
// All 3 return the "default" entity manager
$em = $this->getDoctrine()->getManager();
$em = $this->getDoctrine()->getManager('default');
$em = $this->get('doctrine.orm.default_entity_manager');
// Both of these return the "database2" entity manager
$anotherEm = $this->getDoctrine()->getManager('database2');
$anotherEm = $this->get('doctrine.orm.database2_entity_manager');
}
}
您也可以從symfony的文檔幫助multiple databases。
首先,「簡單的PHP文件」是什麼意思,我不認爲Symfony(2和3)方法允許使用「簡單的PHP文件」。 –
我的意思是一個php類沒有聲明爲控制器@FabriceKabongo –
看看服務配置和依賴注入。 – Rufinus