Search code examples
phpfluent-interface

php mvc model call function on data result


I've got a simple model:

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

I want to do something like this:

$model = new Model;
$model->find('test')->first();

But it's not working

Fatal error: Call to undefined method mysqli_result::first()

It works if I use $model->first($model->find('test')) but it's really ugly. What should I change to achieve $model->find('test')->first() calling?


Solution

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

    You can now use $model->find('test')->first();