我正在嘗試編寫自己的MVC框架using this tutorial。一切正常,我沒有問題完成了教程。嘗試調用構造函數中的方法致命錯誤
但後來我決定使用PDO(PHP數據對象)而不是mysql()函數進行數據庫操作。所以我修改了我的sqlQuery.php文件以使用PDO而不是mysql函數。
sqlQuery.php
<?php
class SQLQuery {
private $_dbHandle;
private $_result;
/**
* Connects to database
*
* @param $address
* @param $account
* @param $pwd
* @param $name
*/
function connect($address, $account, $pwd, $name) {
try{
$this->_dbHandle = new PDO("mysql:host=$address;dbname=$name", $account, $pwd);
}catch (PDOException $e) {
die($e->getCode() . " : " . $e->getMessage());
}
}
/** Disconnects from database **/
function disconnect() {
$this->_dbHandle = null;
}
function get($whereClause = array()) {
$query = "select * from $this->_table";
if(is_array($whereClause) && count($whereClause)){
$query .= " where ";
foreach($whereClause as $column=>$value)
$query .= " $column = $value";
}else if(is_int($whereClause)){
$query .= " where id = $whereClause ";
}
return $this->query($query);
}
/**
* Custom SQL Query
*
* @param $query
* @return array|bool
*/
function query($query) {
$this->_result = $this->_dbHandle->query($query);
$this->_result->setFetchMode(PDO::FETCH_CLASS, $this->_model);
if (preg_match("/select/i",$query)) {
$result = array();
$numOfFields = $this->_result->rowCount();
if($numOfFields > 1){
while($result[] = $this->_result->fetch()){
}
}else{
$result = $this->_result->fetch();
}
return $result;
}
return true;
}
}
現在,當我的控制器當我打印$this->Item->get()
我得到的所有結果在我的數據庫作爲項目示範和$this->Item->get(2)
的對象給我使用id = 2的項目目標預期。
但是,我不喜歡我的API需要調用get()來獲取Items模型的對象的想法,相反,當Item模型初始化時,期望的對象,所以我的API可以是$this->item->mycolumnName
。
要做到這一點,我試圖移動電話get()
在模型構造是這樣的:
model.php
<?php
class Model extends SQLQuery{
protected $_model;
function __construct() {
$this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$this->_model = get_class($this);
$this->_table = strtolower($this->_model)."s";
$this->get();
}
function __destruct() {
}
}
但是這給了我一個致命錯誤
Fatal error: Maximum function nesting level of '256' reached, aborting! in /var/www/html/FitternityAssignment/library/sqlquery.php on line 59
我不知道我做錯了什麼。
哪一行是'sqlquery.php'中的第59行? – Jens
'$ this - > _ result = $ this - > _ dbHandle-> query($ query);' – Mohan