Rozbudowa klasy model do projektu MVC. Dodajemy metodę countWhere – do dzieła!

Pracujemy na materiale z poprzedniej lekcji:

<?php

class ConfigINI {

    //(...)
}

class PDOConnection {

    protected $connection;
    protected $credentials;

    //(...)

}
$conn = new PDOConnection();
$conn->connect();
$conn = $conn->getConnection();

abstract class Model {

    protected static $conn;

    //(...)

}

class PersonModel extends Model {

    protected static $tablename = 'people';
    protected static $keys = ['name', 'age'];

    
}

$person = new PersonModel();
$person->setConn($conn);


$q = $conn->query('SELECT COUNT(*) FROM people WHERE age >= 22');
echo $q->fetch()[0] . "<br>";
//6

Widzimy w jaki sposób tworzy się count-where query. Pora dodać operatory jako stałą do klasy model:

abstract class Model {

    protected static $conn;
    const OPERATORS = ['=', '>=', '>', '<=', '<', '<>'];

    //(...)

}

Teraz możemy pisać metodę:

abstract class Model {

    protected static $conn;
    const OPERATORS = ['=', '>=', '>', '<=', '<', '<>'];

    //(...)

    public static function countWhere($arr){

        [$cname, $operator, $value] = $arr;
        $table = static::$tablename;

        if(!in_array($cname, static::$keys))
            return;
        if(!in_array($operator, self::OPERATORS))
            return;

        $query = "SELECT COUNT(*) FROM {$table} WHERE {$cname} {$operator} {$value}";
        $q = self::$conn->query($query);
        return $q->fetch()[0];
    }

}

Sprawdzamy, czy działa:

//(...)
class PersonModel extends Model {

    protected static $tablename = 'people';
    protected static $keys = ['name', 'age'];

    
}

$person = new PersonModel();
$person->setConn($conn);


$q = $conn->query('SELECT COUNT(*) FROM people WHERE age >= 22');
echo $q->fetch()[0] . "<br>";
//5

echo PersonModel::countWhere(['age', '>=', 22]) . "<br>";
//5