How iamludal/mysql-querybuilder works
Project Type and Purpose
• This is an open‑source PHP library (packaged via Composer) that implements a fluent query‑builder DSL for MySQL (and potentially other PDO‑compatible DBMS).
• Its core responsibility is to let developers construct SQL statements in a type‑safe, object‑oriented way, then compile them to SQL strings or execute them via PDO.
High‑Level Architecture and File Structure
• Top‑Level:
• composer.json / composer.lock – dependency & autoload config
• README.md – overview & usage
• src/ – library source code
• tests/ – PHPUnit test suite
• .github/ – CI & issue templates
• src/ Subfolders:
• Clauses/ – representations of SQL clauses (Where, GroupBy, OrderBy, Limit)
• Statements/ – statement types (Select, Insert, Update, Delete, plus base Statement)
• Exceptions/ – domain exceptions (InvalidQueryException, UnknownType)
• QueryBuilder.php – entry point & factory for statements
• Utils.php – helper functions used across classes
Core Components and Their Relationships
• QueryBuilder
• Factory & context holder (optionally stores a PDO instance & default fetch mode)
• Exposes .select(), .insertInto(), .update(), .deleteFrom()
• Returns a Statement object of the requested type
• Statement (abstract base)
• Owns a list of Clause objects (WHERE, GROUP BY, ORDER BY, LIMIT)
• Defines common methods: setParam(s), execute(), toSQL(), fetch(), rowCount(), getStatement()
• Concrete Statements
• Select, Insert, Update, Delete – each specializes .toSQL() and enforces statement‑specific rules
• Clauses
• Immutable clause objects (Where, OrderBy, GroupBy, Limit)
• Attached to statements via fluent calls: .where(), .orderBy(), .groupBy(), .limit()
• Utils
• String and array manipulations for generating SQL fragments
• Exceptions
• Thrown by QueryBuilder/Statement/Clauses when invalid queries or unsupported types are encountered
• External Service
• PDO – optional injection for direct query execution & fetching
Architectural Patterns and Design Principles
• Fluent Builder Pattern: chaining calls to incrementally build SQL
• Single Responsibility: each Statement and Clause class handles one part of the SQL grammar
• Open/Closed: users can extend by adding new Clause or Statement implementations and registering them
• Dependency Injection: optional PDO injection for testability and decoupling from global state
1. QueryBuilder (Factory)
2. Statement classes (Select, Insert, Update, Delete) inheriting from Statement
3. Clause classes (Where, GroupBy, OrderBy, Limit)
4. Utils (shared library)
5. Exceptions module
6. External PDO service
7. MySQL Database
• Relationships:
• QueryBuilder creates Statement instances
• Statement composes Clause instances
• Statement uses Utils to build SQL strings
• Statement optionally uses injected PDO to execute/fetch
• Statement may throw Exceptions back to the caller
• PDO connects to MySQL DB