The default MVC Model class in PHP

1

I'm studying MVC, I created the abstract Model class to serve as a "template" for the others that can inherit it. I would like an evaluation of the code as, positives and negatives, how best to improve it, etc.

abstract class Model {

private $sql;

protected function setSql($sql_query) {

    return isset($sql_query) ? $this -> sql = $sql_query : false;
}

public function getAll() {

    $query = $this -> db -> prepare($this -> sql);
    try {
        $query -> execute();
        return $query -> fetchAll(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
        die($e -> getMessage());
    }
}

public function getById($id) {

    $query = $this -> db -> prepare($this -> sql);
    $query -> bindValue(1, $id);

    try {
        $query -> execute();
        return $query -> fetch(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
        die($e -> getMessage());
    }
}

public function getBySearch($search_term) {

    $query = $this -> db -> prepare($this -> sql);
    $query -> bindValue(1, $search_term);

    try {
        $query -> execute();
        return $query -> fetchAll(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
        die($e -> getMessage());

    }

}

public function deleteById($id) {/*será implementada*/}
public function updateById($id) {/*será implementada*/}
public function insert() {/*será implementada*/ }

}

And this would be the call in a child class:

public function getUserById($id) {

    $this -> setSql("SELECT * FROM XXX WHERE id = ?");
    return $this -> getById($id);
    
asked by anonymous 10.06.2014 / 04:34

1 answer

3

Positive Points

  • Your Model class is very reminiscent of Data Access Object (DAO) classes, which separates the responsibility of retrieving objects from the responsibility of representing the object.

Negative Points

    It would be legal to abstract the result (each row of the database) instead of returning an associative array

  • You are using SQL, if you create an object to represent the query criteria you will have an independence of SQL and NoSQL database.

Example

I believe that everything should be abstracted, to make development more natural, for example instead of:

echo $model['first_name'].' '.$model['last_name']

you could type

echo $model->full_name;

The function would take care of joining turning the data into more useful information.

The same thing applies to the query, instead of

$person = $personModel->getBySearch("SELECT * FROM person WHERE name = 'Joe'");

You could use

$person = Person::$objects->filter(array('name'=>'Joe'))->first();

Or even

$person = Person::$objects->byName('Joe')->first();

In rails, for example, it creates methods to filter each attribute (automatically)

    
02.08.2014 / 16:54