[英]Opening database connection in controller (connection pattern)
我必須實現數據庫連接模式。 我創建了兩個類:
ConnectionFactory:
<?php
class ConnectionFactory {
protected static $connection;
public function getConnection() {
if (!self::$connection) {
self::$connection = new PDO('mysql:host=localhost;dbname=sapienter', "root", "admin");
}
return self::$connection;
}
}
?>
MySQLService:
<?php
class MySQLService {
protected $connectionFactory;
public function __construct(ConnectionFactory $factory) {
$this->connectionFactory = $factory;
}
public function listItemsForSharerSQL() {
$conn = $this->connectionFactory->getConnection();
$items = ...
return $items;
}
}
?>
我在控制器ItemController中調用這些方法:
<?php
require_once ROOT_DIR . "/models/Item.php";
require_once ROOT_DIR . "/ConnectionFactory.php";
require_once ROOT_DIR . "/MySQLService.php";
class ItemController {
private $data;
public function listItemsForSharer() {
$connFactory = new ConnectionFactory();
$service = new MySQLService($connFactory);
$items = $service->listItemsForSharerSQL();
$this->data = ['items' => $items];
return 'itemslistforsharer-view';
}
}
?>
我不喜歡必須在Controller中實例化一個新的ConnectionFactory的事實。 錯了嗎 我應該更改代碼設計嗎?
您根本在控制器中使用數據庫是錯誤的。 如果從MVC體系結構模式談論控制器,那么其模型工作就是與數據庫進行交互。 控制器中應該只有模型的實例,而數據庫應該沒有。
基本上,在現代MVC框架中,模型正在擴展具有數據庫實例化的基礎模型類。
據我了解,由於要返回一些項目,因此MySQLService
類似於模型,似乎您正在執行數據庫操作,並希望從控制器處理它。 而不是每個模型都有自己的構造函數,而應使用基類。 我建議類似的東西:
class Model {
protected function getAdapter() {
$connection = new ConnectionFactory();
return $connection->getConnection();
}
}
class MySQLService extends Model {
public function listItemsForSharerSQL() {
$this->getAdapter();
$items = ...
return $items;
}
}
所以現在您的控制器只需要
$service = new MySQLService();
當然,您的基類可以將getAdapter()
方法用作構造函數,而無需任何參數,因此您無需將任何內容傳遞給MySQLService
,也不需要在MySQLService
每個方法中調用getAdapther()
。 取決於您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.