0

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?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
dontHaveName
  • 1,899
  • 5
  • 30
  • 54

1 Answers1

0
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();

Andrei
  • 3,434
  • 5
  • 21
  • 44
  • is it either possible to make a method that will return nick and email as one string? Something like `$user = $user->find('fake')->first(); $user->nickAndEmail();` but I can't figure out some logic that will be able to add this method to all results – dontHaveName Sep 29 '15 at 13:59