【问题标题】:php mvc model call function on data resultphp mvc模型调用函数对数据结果
【发布时间】:2015-09-29 13:36:23
【问题描述】:

我有一个简单的模型:

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

【问题讨论】:

    标签: php fluent-interface


    【解决方案1】:
    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();

    【讨论】:

    • 是否有可能制作一种将 nick 和 email 作为一个字符串返回的方法?像$user = $user->find('fake')->first(); $user->nickAndEmail(); 这样的东西,但我想不出一些能够将此方法添加到所有结果中的逻辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    相关资源
    最近更新 更多