PHPackages                             ddbase3/php-struql - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. ddbase3/php-struql

ActiveLibrary[Database &amp; ORM](/categories/database)

ddbase3/php-struql
==================

A PHP implementation of the Struql query language — parse, merge, expand, and translate Struql JSON into SQL.

v1.0.3(1y ago)04MITPHPPHP ^8.1

Since May 19Pushed 1y ago1 watchersCompare

[ Source](https://github.com/ddbase3/php-struql)[ Packagist](https://packagist.org/packages/ddbase3/php-struql)[ RSS](/packages/ddbase3-php-struql/feed)WikiDiscussions v1 Synced today

READMEChangelogDependencies (1)Versions (6)Used By (0)

Struql – Structured Query Logic for PHP
=======================================

[](#struql--structured-query-logic-for-php)

Struql is a modular, extensible, and phase-based query processing framework for PHP. It empowers developers to define, normalize, simplify, and compile structured query logic into executable SQL – all using a clean and extensible handler-based architecture.

---

🌐 Why Struql?
-------------

[](#-why-struql)

Struql was designed to solve a recurring problem: building highly dynamic and structured queries without tying your code to SQL strings or rigid query builders. With Struql, you can:

- Parse structured query inputs from users or APIs
- Normalize and enrich the query logic
- Automatically resolve joins and field variants
- Generate safe and dialect-specific SQL queries

---

📦 Features
----------

[](#-features)

- **Four processing phases**: Parse → Normalize → Simplify → Compile
- **Handler architecture**: Each transformation is modular and isolated
- **JOIN auto-resolution**: Based on smart field inference
- **SQL dialect support**: MySQL, MSSQL, PostgreSQL
- **Composable processors**: Reusable across contexts
- **Readable, testable, and extendable** code

---

🧱 Architecture Overview
-----------------------

[](#-architecture-overview)

```
[ Input Query ]
      ↓
[ Parse Phase ]
      ↓
[ Normalize Phase ]
      ↓
[ Simplify Phase ]
      ↓
[ Compile Phase ]
      ↓
[ SQL String ]

```

Each phase is managed by a `Processor`, which consists of ordered `Handlers`. A handler is a class that inspects and transforms the query object for a specific purpose.

---

🧩 Key Concepts
--------------

[](#-key-concepts)

### ✅ Processors and Handlers

[](#-processors-and-handlers)

Each handler must implement:

- `supportedTypes()` – which input types it processes
- `run(mixed $input, array &$context): mixed` – transformation logic

### 🧠 Phase Responsibilities

[](#-phase-responsibilities)

PhasePurpose`parse`Parses external input (e.g. query strings) into PHP objects`normalize`Expands shorthand field syntax, dollar-fields, top-level filters`simplify`Resolves aliases, inferred joins, expands derived objects`compile`Transforms the object into executable SQL---

🧪 Example Usage
---------------

[](#-example-usage)

```
use Struql\Processor\NormalizePhaseProcessor;
use Struql\Processor\CompilePhaseProcessor;
use Struql\Handler\DollarFieldToFieldHandler;
use Struql\Handler\FieldsToWhereHandler;
use Struql\Handler\SqlCompilerHandler;
use Struql\Handler\SqlDialect;

// Normalization
$normalize = new NormalizePhaseProcessor();
$normalize->addHandler(new DollarFieldToFieldHandler());
$normalize->addHandler(new FieldsToWhereHandler());

$query = $normalize->process([
  'type' => 'selectUser',
  '$user!optional.status' => 'active',
  'limit' => 10,
  'offset' => 20,
  'orderBy' => [
    (object)[ 'type' => 'field', 'table' => 'user', 'name' => 'id', 'direction' => 'DESC' ]
  ]
]);

// Compilation
$compile = new CompilePhaseProcessor();
$compile->addHandler(new SqlCompilerHandler(SqlDialect::MySQL));

$sql = $compile->process($query);
echo $sql;
```

**Output SQL:**

```
SELECT `user`.`id`, `user`.`login`, `user`.`name`
FROM `user`
LEFT JOIN `profile` ON `user`.`id` = `profile`.`user_id`
WHERE `user`.`status` = 'active'
ORDER BY `user`.`id` DESC
LIMIT 10 OFFSET 20
```

---

🛠️ Built-in Handlers
--------------------

[](#️-built-in-handlers)

### Normalize Phase

[](#normalize-phase)

- `DollarFieldToFieldHandler`: Converts `$table!variant.field` to `field` objects with `table`, `name`, and `variant`
- `FieldsToWhereHandler`: Converts top-level field-value pairs to `where` conditions

### Compile Phase

[](#compile-phase)

- `SqlCompilerHandler`: Converts normalized query objects to SQL strings; supports:

    - Joins (INNER, LEFT)
    - Conditions with `AND`, `OR`, `NOT`
    - ORDER BY, GROUP BY, HAVING, LIMIT, OFFSET
    - Dialect-specific quoting

---

🔄 Extending Struql
------------------

[](#-extending-struql)

To add a new transformation or compiler step, create a new handler:

```
class MyCustomHandler extends AbstractHandler {
    public function supportedTypes(): array {
        return ['object'];
    }

    public function run(mixed $input, array &$context): mixed {
        // Transform the $input as needed
        return $input;
    }
}
```

Register it in your processor:

```
$normalize->addHandler(new MyCustomHandler());
```

---

🚀 Use Cases
-----------

[](#-use-cases)

- Backend APIs that accept dynamic filters from users (e.g. dashboards, analytics)
- Middleware layers that convert API calls to database queries
- CMS systems with dynamic content filtering
- Query conversion pipelines for SQL dialect adaptation

---

📁 File Structure
----------------

[](#-file-structure)

```
src/
  Core/
    AbstractHandler.php
    Processor.php
  Handler/
    DollarFieldToFieldHandler.php
    FieldsToWhereHandler.php
    SqlCompilerHandler.php
    SqlDialect.php
  Processor/
    NormalizePhaseProcessor.php
    CompilePhaseProcessor.php

```

---

📋 Future Plans
--------------

[](#-future-plans)

- ✅ Automatic join resolution via used fields
- 🔲 Validation layer for input checking before compilation
- 🔲 Support for INSERT, UPDATE, DELETE queries
- 🔲 Full support for subqueries and expressions

---

📃 License
---------

[](#-license)

This project is open-source and available under the MIT License.

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Create a feature branch and submit a pull request. Please include tests where applicable.

---

🧠 Summary
---------

[](#-summary)

Struql is a powerful and extensible query transformation engine. Its handler-based architecture allows developers to fully control and customize every aspect of query interpretation and SQL generation – from API input to final query execution.

Ideal for teams building APIs, dashboards, CMS backends, or data-driven platforms.

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance46

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

5

Last Release

403d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/122759330?v=4)[Daniel Dahme](/maintainers/ddbase3)[@ddbase3](https://github.com/ddbase3)

---

Top Contributors

[![ddbase3](https://avatars.githubusercontent.com/u/122759330?v=4)](https://github.com/ddbase3 "ddbase3 (2 commits)")

---

Tags

base3-librarybase3-publicbase3-struqlphpparsersqlqueryquery-languagestruql

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ddbase3-php-struql/health.svg)

```
[![Health](https://phpackages.com/badges/ddbase3-php-struql/health.svg)](https://phpackages.com/packages/ddbase3-php-struql)
```

###  Alternatives

[izniburak/pdox

Useful Query Builder, PDO Class for PHP. A simple access to your SQL records.

30221.7k7](/packages/izniburak-pdox)[nilportugues/sql-query-formatter

A very lightweight PHP class that reformats unreadable and computer-generated SQL query statements to human-friendly, readable text.

391.2M29](/packages/nilportugues-sql-query-formatter)[sad_spirit/pg_builder

Query builder for Postgres backed by SQL parser

5940.0k1](/packages/sad-spirit-pg-builder)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
