2015-09-29 7 views
0

У меня есть простая модель:PHP MVC модель вызов функции по данным результатам

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

ответ

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

Теперь вы можете использовать $model->find('test')->first();

+0

хорошо, я просто слишком глуп :-) спасибо – dontHaveName

+0

это либо можно сделать метод, который будет возвращать ник и адрес электронной почты в одну строку? Что-то вроде '$ user = $ user-> find ('fake') -> first(); $ user-> nickAndEmail(); 'но я не могу понять какую-то логику, которая сможет добавить этот метод ко всем результатам – dontHaveName