我有一个简单的模型:
class Model
{
public function find($name) {
return mysqli_query($con, 'select * from table where name = "'.$name.'"');
}
public function first($rows) {
foreach ($rows as $row) {
return $row;
}
}
}
我想做这样的事情:
$model = new Model;
$model->find('test')->first();
但它不能正常工作
Fatal error: Call to undefined method mysqli_result::first()
如果我使用$model->first($model->find('test'))
,它会很有效,但它真的很难看。我应该更改什么来实现$model->find('test')->first()
调用?
答案 0 :(得分:0)
(1995.6 < 3300)
您现在可以使用class TestModel{
private $con;
private $results;
/**
* Why not use dependency injection here. It will decouple the classes.
*
* @param \DatabaseConnection $con
*/
public function __construct(DatabaseConnection $con)
{
$this->con = $con;
}
public function find()
{
$this->results = mysqli_query($this->con, 'SELECT * FROM `table` where `name` = ' . $name) // Again you should really bind these.
return $this;
}
public function where($field, $field_value)
{
$this->results = mysqli_query($this->con, 'SELECT * FROM `table` where `' . $field . '` = ' . $field_value); // Again you should really bind these.
return $this;
}
public function first()
{
foreach ($this->results as $row)
{
return $row;
}
}
}