Web應用通常使用數據庫存儲數據,LEMP中的 M 即指數據庫(默認爲 MySQL)。PHP框架Symfony是通過集成的第三方庫 Doctrine 與數據庫交互(通過Composer安裝)。Doctrine支持2中形式 Doctrine ORM 和 Doctrine DBAL。DBAL
是Database Abstraction Layer
(數據庫抽象層)的縮寫,Doctrine DBAL支持原生的SQL語句。
本文記錄如何在Symfony 4中通過Doctrine DBAL進行數據庫的CRUD操作。(與Symfony 3相比,變動很大)
Prerequisite
本人Blog Installing And Setting Up The Symfony Framework On CentOS 7 詳細記錄了Symfony、Composer的安裝、配置過程。
LEMP環境信息
Info | Details |
---|---|
OS Version | CentOS Linux release 7.4.1708 (Core) |
Kernel Version | 3.10.0-693.21.1.el7.x86_64 |
Nginx | 1.13.12 |
MySQL | 5.7.21 |
PHP | 7.2.4 |
Composer | 1.6.4 |
通過annotation
配置URL路由規則
|
|
Doctrine Installation
通過如下命令安裝 Doctrine
|
|
操作過程
|
|
DBAL configuration
Testing Database Info
創建測試帳號、數據庫,具體信息如下
Item | Detial |
---|---|
Host | 127.0.0.1 |
Port | 3306 |
Username | symfony |
Password | [email protected]_dbal |
Database | dbal |
SQL語句如下
|
|
操作過程
|
|
DBAL configuration
配置數據庫有2種方式:
- 項目目錄下的文件
.env
- 項目目錄下的文件
config/packages/doctrine.yaml
按照文檔 Installing & Setting up the Symfony Framework 創建項目後(此處項目名axdlog
),目錄中生成一個名爲.env
的隱藏文件,配置指令是DATABASE_URL
。
|
|
此處應爲
|
|
但這種配置方式有一個問題,如果用戶密碼含有:
、@
等特殊字符,解析時可能會出錯。
通過文件doctrine.yaml
配置更爲妥當,具體配置參照官方文檔 DoctrineBundle Configuration (“doctrine”)。
配置信息如下
|
|
|
|
在項目所在目錄中執行
|
|
在瀏覽器URL中輸入對應的URL地址即可看到相關輸出信息。
CRUD
以下操作命令參考自Doctrine官方文檔 4. Data Retrieval And Manipulation。
說明:return new Response()
只能返回字符串,無法返回數組,故而使用var_dump()
打印。
數據庫增刪改查,以測試數據庫dbal
中的province
數據表為例:
插入測試數據
|
|
|
|
Retrieve Data
fetchColumn
fetchColumn($column)
- Retrieves only one column of the next row specified by column index. Moves the pointer forward one row, so that consecutive calls will always return the next row.
|
|
fetchArray
fetchArray()
: Numeric index retrieval of first result row of the given query:
|
|
|
|
fetchAssoc
fetchAssoc()
: Retrieve assoc row of the first result row.
|
|
|
|
fetchAll
fetchAll($fetchStyle)
- Retrieves all rows from the statement.
|
|
|
|
Update Data
executeUpdate($sql, $params, $types)
- Create a prepared statement for the passed SQL query, bind the given params with their binding types and execute the query. This method returns the number of affected rows by the executed query and is useful forUPDATE
,DELETE
andINSERT
statements.
Executes a prepared statement with the given SQL and parameters and returns the affected rows count
|
|
|
|
Insert Data
insert(): Insert a row into the given table name using the key value pairs of data.
|
|
|
|
Delete
delete()
: Delete all rows of a table matching the given identifier, where keys are column names.
|
|
|
|
References
- Databases and the Doctrine ORM
- How to Use Doctrine DBAL
- The VarDumper Component
- Data Retrieval And Manipulation
Change Logs
- 2016.08.24 12:39 Wed Aisa/Shanghai
- 初稿完成
- 2018.04.14 19:13 Sat America/Boston
- 更新、勘誤,遷移到新Blog