Untitled

 avatar
unknown
plain_text
5 months ago
1.8 kB
4
Indexable
<?php
class Table {
    private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }

    public function getName(): string {
        return $this->name;
    }
}



class Model {
    protected Table $table;
    protected string $query = '';
    protected array $joins = [];

    public function __construct(string $tableName) {
        $this->table = new Table($tableName);
    }

    public function select(): self {
        $this->query = "SELECT * FROM {$this->table->getName()}";
        return $this;
    }

    public function where(string $condition): self {
        $this->query .= " WHERE {$condition}";
        return $this;
    }


    public function buildQuery(): self {
        foreach ($this->joins as $join) {
            $this->query .= " " . $join->getJoinClause();
        }
        return $this;
    }

    public function getQuery(): string {
        return $this->query;
    }
}

// Example: Extended User Model
class User extends Model {
    public function __construct() {
        parent::__construct("users");
    }
}

// Example: Extended Product Model
class Product extends Model {
    public function __construct() {
        parent::__construct("products");
    }
}

// Example Usage
$userModel = new User();
$query = $userModel
    ->select()
    ->where("users.id = 1")
    ->getQuery();

echo $query;
// Outputs: SELECT * FROM users INNER JOIN orders ON users.id = orders.user_id WHERE users.id = 1
echo "\n";
$productModel = new Product();
$query = $productModel
    ->select()
    ->where("categories.name = 'Electronics'")
    ->buildQuery()
    ->getQuery();

echo $query;
// Outputs: SELECT * FROM products LEFT JOIN categories ON products.category_id = categories.id WHERE categories.name = 'Electronics'
?>
Editor is loading...
Leave a Comment