Current Path : /data/web/virtuals/51568/virtual/www/subdom/srps/src/db/ |
Current File : /data/web/virtuals/51568/virtual/www/subdom/srps/src/db/DbModel.php |
<?php namespace app\db; use app\Model; use app\Application; abstract class DbModel extends Model { abstract public function tableName(): string; abstract public function attributes(): array; abstract public function primaryKey(): string; /* pomocne funkce do array_map */ private static function params($x) { return ":$x"; } private static function attr($x) { return "$x = :$x"; } public function save() { $tableName = $this->tableName(); $attributes = $this->attributes(); $params = array_map('self::params', $attributes); $statement = Application::$app->db->prepare(" INSERT INTO $tableName (".implode(', ', $attributes) . ") VALUES (".implode(', ', $params) . ") "); foreach($attributes as $attribute) { $statement->bindValue(":$attribute", $this->{$attribute}); } $statement->execute(); return true; } public function findOne($where) { $tableName = static::tableName(); $attributes = array_keys($where); $sql = implode ("AND ", array_map('self::attr', $attributes)); $statement = Application::$app->db->prepare(" SELECT * FROM $tableName WHERE $sql "); foreach($where as $key => $item) { $statement->bindValue(":$key", $item); } $statement->execute(); return $statement->fetchObject(static::class); } }