php mvc模型调用数据结果函数

php mvc model call function on data result

我有一个简单的模型:

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() 调用?

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;
        }
    }
}

您现在可以使用 $model->find('test')->first();