我正在工作/学习如何mvc项目结构。我有一个数据库连接器,一个注册表类,一个模型和一个应用程序模型。我把所有这些都放在一个地方检查它是否正常工作。问题是我执行时会遇到这三个错误。
<?php
class db
{
protected $conn;
protected $host, $username, $password, $database;
public function __construct($host, $username, $password, $database)
{
$this->conn = new mysqli($host, $username, $password, $database)
OR die("There was a problem connecting to the database");
return true;
}
public function query($sql)
{
$result = $this->conn->query($sql);
if (!$result) {
die('Invalid query:');
}
return $result;
}
public function escape($value)
{
return $this->conn->real_escape_string($value);
}
public function countAffected()
{
return $this->conn->affected_rows;
}
public function getLastId()
{
return $this->conn->insert_id;
}
public function __destruct()
{
$this->conn->close()
OR die("Problem disconnecting from the database");
}
}
final class registry
{
private $data = array();
public function get($key)
{
return (isset($this->data[$key]) ? $this->data[$key] : null);
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function has($key)
{
return isset($this->data[$key]);
}
}
abstract class Model
{
protected $registry;
public function __construct($registry)
{
$this->registry = $registry; // Undefined variable: registry
}
public function __get($key)
{
return $this->registry->get($key);
}
public function __set($key, $value)
{
$this->registry->set($key, $value);
}
}
class MemberModel extends Model
{
public function getMember()
{
$result = $this->query("SELECT * FROM members"); //Call to undefined method MemberModel::query()
return $result;
}
}
// DB
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'pcaframework');
$registry = new registry();
// Database
$db = new db(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
$membermodel = new MemberModel(); //Missing argument 1 for Model::__construct()
$allMembers = $membermodel->getMember();
while ($row = mysqli_fetch_assoc($allMembers)) {
echo "First Name: " . $row['name'] . "<br />";
echo "Last Name: " . $row['email'] . "<br />";
echo "<hr />";
}
我已对代码中的错误进行了评论,以准确标记错误发生的位置。
答案 0 :(得分:1)
解决方案:
$result = $this->query("SELECT * FROM members"); //Call to undefined method MemberModel::query()
替换为:
$result = $this->conn->query("SELECT * FROM members");
你忘了&#34; - &gt; conn-&gt;&#34;。
解决方案:
$this->registry = $registry; // Undefined variable: registry
和
$membermodel = new MemberModel(); //Missing argument 1 for Model::__construct()
只需将$ last替换为$ registry var作为新类的参数:
$membermodel = new MemberModel($registry);
您正在调用需要参数的构造函数,但您并未引用该参数。