我正在尝试编写自己的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