【发布时间】:2020-12-21 01:52:20
【问题描述】:
我最近开始通过使用更多继承来更新我在 Apache 服务器上的 Api 代码。由于缺乏经验,我过去使用它有点小心。
问题是我注意到为每个模型实例设置了一个新的数据库连接。所以我在Static 变量上创建了一个替代连接以传递给每个模型。我的问题是,如果我在下面的示例中使用__construct 创建连接,每个新模型实例上的多个数据库连接会导致问题吗?
class ApiEnterprises {
protected $db;
private $table;
public function __construct(){
$this->messager = new Messager();
$this->table = 'enterprisetable';
$this->db = new \mysqli(DB_HOST, DB_USERRW, DB_PASSWRW, DB_DBASE);
if ($this->db === NULL || !$this->db) {
// set response code
echo $this->messager->databaseFailed();
}
}
}
class ApiUsers {
protected $db;
private $table;
public function __construct(){
$this->messager = new Messager();
$this->table = 'usertable';
$this->db = new \mysqli(DB_HOST, DB_USERRW, DB_PASSWRW, DB_DBASE);
if ($this->db === NULL || !$this->db) {
// set response code
$this->messager->databaseFailed();
}
}
}
另外,Static 变量会更安全吗?因为我可以在 Controller __destruct 方法中删除它。
class Database {
static $connect;
protected static function conn() {
self::$connect = new \mysqli(DB_HOST, DB_USERRW, DB_PASSWRW, DB_DBASE);
return self::$connect;
}
}
class ApiUserController extends Database {
private $user_model;
private $enterprise_model;
public $connection;
public function __construct($data){
$this->connection = parent::conn();
//pass connection to models
$this->user_model = new ApiUsers($this->connection);
$this->enterprise_model = new ApiEnterprises($this->connection);
}
}
【问题讨论】:
-
可能值得看看依赖注入(例如stackoverflow.com/questions/10064970/php-dependency-injection)并注入数据库连接。这使得测试变得更加容易(除其他外)。
标签: php inheritance mysqli