Kontynuujemy prace nad naszym modelem do projektu MVC. Tworzymy metody count i avg. Do dzieła.

Pracujemy na materiale z poprzednich lekcji:

<?php

class ConfigINI {

    //(...)
}

class PDOConnection {

    //(...)

}

$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');
echo $q->fetch()[0] . "<br>";
//6

$q = $conn->query('SELECT AVG(AGE) FROM people');
echo $q->fetch()[0] . "<br>";
//23.0000

Dodaliśmy tutaj SQLowe queries, żeby pokazać, jak to wygląda. Teraz piszemy dedykowane metody:

abstract class Model {

    protected static $conn;

    //(...)

    public static function count(){
        $table = static::$tablename;
        $query = "SELECT COUNT(*) FROM {$table}";
        $q = static::$conn->query($query);
        return $q->fetch()[0]; 
    }

    

}

class PersonModel extends Model {

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

}

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


echo $person::count() . "<br>";
//6
echo PersonModel::count() . "<br>";
//6

Z metodą AVG będzie podobnie:

abstract class Model {

    protected static $conn;

   //(...)

    public static function avg($col){
        $table = static::$tablename;
        if(in_array($col, static::$keys)){
            $query = "SELECT AVG({$col}) FROM {$table}";
            $q = static::$conn->query($query);
            return $q->fetch()[0]; 
        }
    }

}

class PersonModel extends Model {

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

    
}

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


echo $person::avg("age") . "<br>";
//23.0000
echo PersonModel::avg("age") . "<br>";
//23.0000

Modele będziemy rozbudowywać.