Micro-ORM/index.php

64 lines
1.5 KiB
PHP
Raw Normal View History

2021-02-26 21:00:00 +00:00
<?php
2021-02-26 21:11:56 +00:00
namespace Sieciech\Orm8;
2021-02-26 21:25:35 +00:00
use PDO;
2021-02-26 21:00:00 +00:00
interface ISqlBase {
public function Get(): string;
//public function Insert(): string;
//public function Update(): string;
//public function Delete(): string;
}
2021-02-26 21:24:44 +00:00
class ConnectionManager {
private static $connection;
public static function connect(string $connectionString) {
self::$connection = new PDO($connectionString);
}
public static function Query(string $query, $params, $output = 'stdObject') {
$stmt = self::$connection->prepare($query);
$stmt->execute($params);
2021-02-27 09:10:52 +00:00
2021-02-27 09:49:56 +00:00
$stmt->setFetchMode(PDO::FETCH_INTO, new $output());
2021-02-27 09:10:52 +00:00
return $stmt->fetch();
2021-02-26 21:24:44 +00:00
}
}
2021-02-26 21:08:57 +00:00
abstract class BaseModel {
2021-02-26 21:39:06 +00:00
protected static $sql = null;
2021-02-26 21:00:00 +00:00
public static function Get(int $id) {
2021-02-27 08:43:52 +00:00
static::Initialize();
2021-02-26 21:24:44 +00:00
return ConnectionManager::Query(
self::$sql->Get(),
2021-02-27 08:46:04 +00:00
['id' => $id],
2021-02-26 21:24:44 +00:00
get_called_class());
2021-02-26 21:00:00 +00:00
}
2021-02-26 21:39:06 +00:00
2021-02-27 08:39:22 +00:00
abstract public static function Initialize();
2021-02-26 21:00:00 +00:00
}
class JobSql implements ISqlBase {
public function Get(): string {
2021-02-26 21:24:44 +00:00
return "Select * from jobs where id = :id";
2021-02-26 21:00:00 +00:00
}
}
class Job extends BaseModel {
2021-02-27 08:52:19 +00:00
public int $id;
public float $budget;
2021-02-27 08:35:47 +00:00
public static function Initialize() {
if (self::$sql === null) {
self::$sql = new JobSql();
}
2021-02-26 21:00:00 +00:00
}
}
2021-02-26 21:26:48 +00:00
$dns = 'pgsql:host=localhost;port=5432;dbname=dynamic_dev;user=test;password=pass123';
2021-02-26 21:24:44 +00:00
ConnectionManager::Connect($dns);
2021-02-26 21:11:56 +00:00
echo "
2021-02-26 21:00:00 +00:00
2021-02-26 21:11:56 +00:00
";
2021-02-26 21:39:06 +00:00
var_dump(Job::Get(10));
2021-02-26 21:11:56 +00:00
echo "
";