PHP MVC -应用model's方法从数据库的结果


php mvc - apply model's methods to result from db

在许多php框架中,我们可以这样做:

class Test extends Model
{
    protected $first;
    protected $second;
    public function getAllAttributes() {
        return $this->first.','.$this->second;
    }
}

如何在我自己的解决方案中做到这一点?我当前的模型:

class Model
{
    // ..
    public function all() {
        return mysqli_query($con, 'select * from '.$this->table);
    }
}

用法:

$test = new Test();
$result = $test->all();
foreach ($result as $t) {
    echo $t->getAllAttributes();
}

我理解你想从MySQL查询中创建当前类的对象,而不需要在每个模型中再次处理查询生成和对象实例化。

你描述的模式,模型负责自己加载,被称为Active Record,它是由Ruby on Rails流行起来的,然后在CakePHP和Laravel等PHP框架中进行了改编。

没有单一的解决方案来实现它,看看这些框架的代码来了解它们是如何工作的。

重要的部分是模型必须以某种方式描述自己,即从数据库加载哪些属性,它们的数据类型是什么,使用哪个表。这可以基于MySQL中的DESCRIBE $table结果,通过"annotation"和反射,或者显式地使用代码。