PHPackages                             hwalde/pooq - 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. hwalde/pooq

ActiveLibrary

hwalde/pooq
===========

0.2.0(5y ago)128BSD-3-ClausePHP

Since Jul 9Pushed 3y agoCompare

[ Source](https://github.com/hwalde/pooq)[ Packagist](https://packagist.org/packages/hwalde/pooq)[ RSS](/packages/hwalde-pooq/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

POOQ - PHP Object Oriented Querying
===================================

[](#pooq---php-object-oriented-querying)

POOQ generates PHP code from your database and lets you build type safe SQL queries through its fluent API.

[![Minimum PHP Version](https://camo.githubusercontent.com/1e3b70374ce5a22774aa3385ec7b561e59b8f8c6a75da5d41cb46fcbe55e6a8b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344253230372e332d3838393242462e7376673f7374796c653d666c61742d737175617265)](https://php.net/)

WARNING: POOQ is currently in **alpha** stage! Expect API changes. Expect bugs! Do not use it in production!

Benefits
--------

[](#benefits)

- It creates PHP code from your database.
- It can map the result of queries to objects.
- It allows you to write type-safe sql-queries.
- You won't run into typical ORM problems when it comes to more complicated queries (unexpected behavior or performance problems which need deep insight knowledge into your ORM software to solve)

Requirements
------------

[](#requirements)

- PDO with MySQL (and should work with MariaDB as well)

Installation
------------

[](#installation)

I recommend to use [Composer](https://getcomposer.org/) for installation:

```
composer require hwalde/pooq
```

Then use [Composers autoload functionality](https://getcomposer.org/doc/01-basic-usage.md#autoloading) to include POOQ into your projects:

```
require __DIR__ . '/vendor/autoload.php';
```

Example usage
-------------

[](#example-usage)

### Querying

[](#querying)

#### Initialize for querying

[](#initialize-for-querying)

Before querying you need to initialize POOQ once.

```
\POOQ\POOQ::initialize('database_name', 'username', 'password', 'hostname', 3306);
```

Alternatively an existing [PDO](https://www.php.net/manual/en/book.pdo.php) can be used:

```
\POOQ\POOQ::initializeUsingExistingPdo($yourPdoObject);
```

#### Creating a select query

[](#creating-a-select-query)

```
$t = Thread::as('t'); // Creates an alias name

echo select($t->title(), $t->lastPoster(), $t->postUserName(), $t->replyCount(), $t->threadId())
    ->from($t)
    ->where($t->forumId()->eq(value($forumId)))
    ->order($t->threadId()->desc())
    ->limit(10)
    ->offset(0)
    ->getSql();
```

Outputs:

```
SELECT `t`.`title` as `title`, `t`.`lastposter` as `lastposter`, `t`.`postusername` as `postusername`, `t`.`replycount` as `replycount`, `t`.`threadid` as `threadid`
FROM thread t
WHERE `t`.`forumid` = 2
ORDER BY `t`.`threadid` DESC
LIMIT 10
OFFSET 0
```

Alias names are optional. You can always use the models directly:

```
echo select(Thread::title(), Thread::lastPoster())
    ->from(Thread::class)
    // ...
```

Outputs:

```
SELECT `thread`.`title` as `title`, `thread`.`lastposter` as `lastposter`
FROM `thread`
...
```

#### Mapping results to objects (so called Records)

[](#mapping-results-to-objects-so-called-records)

```
$f = Forum::as('f');
$t = Thread::as('t');

$resultList = select($f, $t->title()) // Select all fields of Forum and the title field of Thread
    ->from($t)
    ->innerJoin($f)->on($f->forumid()->eq($t->forumid())) // "INNER JOIN forum f ON `f`.`forumid` = `t`.`forumid`"
    ->fetchAll(); // Executes the query and returns ResultList

/** @var ThreadRecord[] $threadRecordList */
$threadRecordList = $resultList->into($t); // Maps all Thread fields of ResultList into ThreadRecordList

foreach($threadList as $thread) { // for each row
    echo $thread->getTitle(); // output the title
}
```

#### Records can be optionally inserted/updated/refreshed/deleted in an ORM fashion

[](#records-can-be-optionally-insertedupdatedrefresheddeleted-in-an-orm-fashion)

```
// note: this is only supported for tables containing a primary-key

$record->refresh(); // Reload the record from the database
$record->store(); // insert or update the record to the database
$record->delete(); // deletes this record in the database
```

#### Converting Records to arrays

[](#converting-records-to-arrays)

```
$array = $recordList->toAssoc();  // Maps entire record-list
$array = $record->toAssoc(); // Maps only a single record
```

POOQ can handle queries with overlapping column names (from different tables). For example, if forum and thread would both have a column "title" then each value would still be mapped to the correct object.

#### Execute update queries

[](#execute-update-queries)

```
update(Forum::class)
    ->set(Forum::title(), 'New title')
    ->set(Forum::description(), 'Lorem ipsum ..')
    ->where(Forum::forumId()->eq(value(123)))
    ->execute();
```

executes query:

```
UPDATE forum
SET `title` = 'New title',
SET `description` = 'Lorem ipsum ..'
WHERE `id` = 123
```

Using subqueries in update:

```
update(Thread::class)
    ->set(Thread::forumId(),
        select(Forum::forumId())
            ->from(Forum::class)
            ->where(Forum::title()->eq(value('Sample title')))
    )
    ->where(Thread::threadId()->eq(value(123)))
    ->execute();
```

executes query:

```
UPDATE forum
SET `forumId` = (SELECT `forum`.forumId` FROM `forum` WHERE `forum`.`title` = 'Sample title')
WHERE `id` = 123
```

#### Custom WHERE-clauses

[](#custom-where-clauses)

Not everything is implemented yet.. so being able to write custom where clauses is quite useful:

```
delete(Session::class)
    ->where(new SimpleCondition(Session::creationDatetime()->toSql() . ' < ' . value($dateTime->format('Y-m-d H:i:s'))->toSql()))
    ->execute();
```

### Code Generation

[](#code-generation)

```
$config = new \POOQ\CodeGeneration\CodeGeneratorConfig(__DIR__.DIRECTORY_SEPARATOR.'gensrc');
$config->setCopyrightInformation(
 'userId',
        'display_order' => 'displayOrder',
        'accessmask' => 'accessMask',
        'product' => 'product',
    ]
);

// This is optional:
$businesslogicFolderPath = __DIR__.'/test/businesslogic';
$config->setModelName2NamespaceMap(new \POOQ\CodeGeneration\ModelName2NamespaceMap(
    [
        // Name of model class => NamespaceObject-object
        'Post' => new \POOQ\CodeGeneration\NamespaceObject(
            'businesslogic\\post',
            $businesslogicFolderPath.'/post'
        ),
        'Forum' => new \POOQ\CodeGeneration\NamespaceObject(
            'businesslogic\\forum',
            $businesslogicFolderPath.'/forum'
        ),
    ]
));
$generator = new \POOQ\CodeGeneration\CodeGenerator($config);
$generator->convertDatabase('database_name', 'username', 'password', 'hostname', 3306);
```

Contribution
------------

[](#contribution)

Feel free to improve POOQ and send me your Pull Requests. Don't worry about code style or anything else. I can still adapt your changes if necessary.
I'm happy about every contribution.

Feel free to ask me anything!

Have a nice day!

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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

Unknown

Total

1

Last Release

2131d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/add9f890078f12af912417780d3633d1c66b621c198cd33c68d3593938df2f6c?d=identicon)[hwalde](/maintainers/hwalde)

---

Top Contributors

[![hwalde](https://avatars.githubusercontent.com/u/40671872?v=4)](https://github.com/hwalde "hwalde (41 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hwalde-pooq/health.svg)

```
[![Health](https://phpackages.com/badges/hwalde-pooq/health.svg)](https://phpackages.com/packages/hwalde-pooq)
```

PHPackages © 2026

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