PHPackages                             greatcode/controller-global - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. greatcode/controller-global

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

greatcode/controller-global
===========================

Base Library Controller Global for GC

v0.1.1(2mo ago)052↓50%[2 PRs](https://github.com/Great-Code-Team/controller-global/pulls)MITPHPPHP &gt;=8.2CI passing

Since Feb 18Pushed 2mo agoCompare

[ Source](https://github.com/Great-Code-Team/controller-global)[ Packagist](https://packagist.org/packages/greatcode/controller-global)[ RSS](/packages/greatcode-controller-global/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (5)Dependencies (5)Versions (9)Used By (0)

controller-global
=================

[](#controller-global)

Base Library Controller Global for GC — a PHP utility library providing a PDO wrapper, generic DML/SELECT helpers, AES-256-CBC encoding, and a POS-group integrator client.

**Requirements:** PHP &gt;= 8.2, ext-pdo, ext-pdo\_sqlite, ext-openssl, ext-curl, guzzlehttp/guzzle ^7.10

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

[](#installation)

```
composer require greatcode/controller-global
```

---

CtrlGlobal
----------

[](#ctrlglobal)

General-purpose controller with DML helpers, SELECT wrappers, HTTP client wrappers, and AES-256-CBC encode/decode. Resolves its `Connection` automatically.

### Instantiation

[](#instantiation)

```
use Greatcode\ControllerGlobal\CtrlGlobal;

// From a Connection instance
$ctrl = new CtrlGlobal($connection);

// From a config array (passed to Connection::fromConfig)
$ctrl = new CtrlGlobal(['driver' => 'sqlite', 'dbname' => ':memory:']);

// With a custom AES encryption key
$ctrl = new CtrlGlobal($connection, 'my-secret-key');

// From environment variables / global $cfg array
$ctrl = new CtrlGlobal();

// Singleton
$ctrl = CtrlGlobal::getInstance();
```

When constructed with `null` (default), it checks for a global `$cfg['db']` array first, then falls back to `Connection::fromEnv()`.

The encryption key is resolved in this order:

1. Explicit `$encryption_key` constructor argument
2. `ENCRYPTION_KEY` environment variable
3. Fallback value `'secret'`

### DML

[](#dml)

#### insert()

[](#insert)

```
$ctrl->insert('users', [
    'name'  => 'Alice',
    'email' => 'alice@example.com',
]);
// returns 'success'
```

#### insertAll()

[](#insertall)

Insert multiple rows in a single statement.

```
$ctrl->insertAll('users', [
    ['name' => 'Alice', 'email' => 'alice@example.com'],
    ['name' => 'Bob',   'email' => 'bob@example.com'],
]);
```

#### update()

[](#update)

```
$ctrl->update(
    'users',
    ['email' => 'new@example.com'],  // SET
    ['id'    => 42]                  // WHERE (AND-joined)
);
```

#### delete()

[](#delete)

```
$ctrl->delete('users', ['id' => 42]);
```

#### deleteAll()

[](#deleteall)

Delete multiple rows, each matched by its own condition set (conditions within a row are AND-joined; rows are OR-joined).

```
$ctrl->deleteAll('users', [
    ['id' => 1],
    ['id' => 2],
]);
```

### SELECT

[](#select)

#### GetGlobalFilter()

[](#getglobalfilter)

Execute a SELECT and return all rows as associative arrays. Supports both positional (`?`) and named (`:key`) bindings.

```
$rows = $ctrl->GetGlobalFilter('SELECT * FROM users WHERE active = ?', [1]);

$rows = $ctrl->GetGlobalFilter(
    'SELECT * FROM users WHERE role = :role',
    [':role' => 'admin']
);
```

#### runSql()

[](#runsql)

Same behaviour as `GetGlobalFilter` — execute SQL and return all rows.

```
$rows = $ctrl->runSql('SELECT * FROM orders WHERE status = ?', ['pending']);
```

#### getName()

[](#getname)

Return the `name` column of the first result row, or an empty string if no rows match.

```
$name = $ctrl->getName('SELECT name FROM categories WHERE id = ?', [5]);
```

### Encoding

[](#encoding)

AES-256-CBC encode/decode. The key is determined by the constructor (see Instantiation above).

```
$token   = $ctrl->encode('sensitive-value');
$decoded = $ctrl->decode($token); // 'sensitive-value'
```

Two instances using different keys will produce different ciphertext for the same input and cannot decode each other's output.

### HTTP client

[](#http-client)

Thin wrappers around a shared `GuzzleHttp\Client` singleton. All methods return a PSR-7 `ResponseInterface`.

```
$response = $ctrl->httpGet('https://api.example.com/items');
$response = $ctrl->httpPost('https://api.example.com/items', ['json' => ['name' => 'foo']]);
$response = $ctrl->httpPut('https://api.example.com/items/1', ['json' => ['name' => 'bar']]);
$response = $ctrl->httpPatch('https://api.example.com/items/1', ['json' => ['name' => 'baz']]);
$response = $ctrl->httpDelete('https://api.example.com/items/1');
```

The underlying `GuzzleHttp\Client` instance is a static singleton shared across all `CtrlGlobal` instances:

```
$client = $ctrl->getHttpClient(); // GuzzleHttp\Client
```

---

Connection
----------

[](#connection)

`Connection` extends `PDO` with safe defaults and convenience factory methods.

**Default PDO attributes set on every connection:**

AttributeValue`ATTR_ERRMODE``ERRMODE_EXCEPTION``ATTR_DEFAULT_FETCH_MODE``FETCH_ASSOC``ATTR_EMULATE_PREPARES``false``ATTR_PERSISTENT``false`### Direct constructor

[](#direct-constructor)

```
use Greatcode\ControllerGlobal\Connection;

$conn = new Connection('mysql:host=127.0.0.1;dbname=mydb;charset=utf8mb4', 'user', 'pass');
```

Override any default attribute:

```
$conn = new Connection('sqlite::memory:', options: [PDO::ATTR_EMULATE_PREPARES => true]);
```

### fromConfig()

[](#fromconfig)

Build a connection from an associative array. Supported drivers: `mysql`, `pgsql`, `sqlite`.

```
$conn = Connection::fromConfig([
    'driver'   => 'mysql',       // default: 'mysql'
    'host'     => '127.0.0.1',   // default: 'localhost'
    'port'     => 3306,
    'dbname'   => 'mydb',
    'charset'  => 'utf8mb4',     // default: 'utf8mb4'
    'username' => 'user',
    'password' => 'pass',
    'options'  => [],            // extra PDO attributes
]);

// SQLite in-memory
$conn = Connection::fromConfig(['driver' => 'sqlite', 'dbname' => ':memory:']);
```

### fromEnv()

[](#fromenv)

Reads connection parameters from environment variables.

Env varDefault`DB_DRIVER``mysql``DB_HOST``127.0.0.1``DB_PORT``3306``DB_NAME`*(empty)*`DB_CHARSET``utf8mb4``DB_USER`*(empty)*`DB_PASSWORD`*(empty)*```
$conn = Connection::fromEnv();
```

### getInstance() — singleton

[](#getinstance--singleton)

Returns the same `Connection` instance across calls. Useful for sharing a single connection throughout a request lifecycle.

```
$conn = Connection::getInstance('mysql:host=127.0.0.1;dbname=mydb', 'user', 'pass');

// Subsequent calls with any arguments return the first instance
$same = Connection::getInstance();
```

### transaction()

[](#transaction)

Wraps a callable in a database transaction. Commits on success, rolls back and re-throws on any exception.

```
$conn->transaction(function (Connection $db) {
    $db->exec("INSERT INTO orders (total) VALUES (100)");
    $db->exec("UPDATE stock SET qty = qty - 1 WHERE id = 5");
});

// Return values are passed through
$id = $conn->transaction(fn(Connection $db) => $db->lastInsertId());
```

---

CtrlGroupPos
------------

[](#ctrlgrouppos)

HTTP client for a remote POS-group integrator service.

```
use Greatcode\ControllerGlobal\CtrlGroupPos;

$pos = new CtrlGroupPos('PC-001', 'https://integrator.example.com');
```

### Methods

[](#methods)

MethodDescription`getGroupPos(array $params)`Query POS user data. Required keys: `group_pos`, `browser`, `waktu`.`updateLoginProcess($id, $status)`Update the login status of a POS session.`updateLastDate($id, $last_data)`Update the last-data timestamp for a POS entry.`updatePOSLastDate(array $datas)`Bulk-update POS last dates via JSON POST. Each item needs `status` and `data`.`updatePosToken($token, $id, $status)`Update the token associated with a POS session.`updateBranchId($branchID, $id)`Update the branch ID for a POS entry.`saveToLocal($table, $arFieldValues)`Insert rows into a local table via `CtrlGlobal::insertAll()`. Returns `bool`.---

Logger
------

[](#logger)

Logger is a facade for Monolog. It is initialized in `CtrlGlobal::initialize()`.

MethodDescription`Log::initialize($name, $config)`Initialize the logger. See `Logger::__construct()` for `$config` details.`Log::getInstance()`Get the logger instance.`Log::debug($message)`Log debug.`Log::info($message)`Log info.`Log::warning($message)`Log warning.`Log::error($message)`Log error.`Log::fatal($message)`Log fatal.---

Running tests
-------------

[](#running-tests)

The test suite is split into two suites: **Unit** (SQLite, no external services) and **Integration** (real MySQL).

### Unit tests

[](#unit-tests)

```
composer install
./vendor/bin/phpunit --testsuite Unit
```

### Integration tests (MySQL)

[](#integration-tests-mysql)

Requires `ext-pdo_mysql`. Set `DB_NAME` at minimum; all 23 tests skip automatically when it is absent.

```
export DB_DRIVER=mysql
export DB_HOST=127.0.0.1
export DB_PORT=3306
export DB_NAME=test_db
export DB_USER=root
export DB_PASSWORD=secret

./vendor/bin/phpunit --testsuite Integration --filter Mysql
```

### Integration tests (PostgreSQL)

[](#integration-tests-postgresql)

Requires `ext-pdo_pgsql`. Set `PGSQL_NAME` at minimum; all 23 tests skip automatically when it is absent.

```
export PGSQL_HOST=127.0.0.1
export PGSQL_PORT=5432
export PGSQL_NAME=test_db
export PGSQL_USER=postgres
export PGSQL_PASSWORD=secret

./vendor/bin/phpunit --testsuite Integration --filter Pgsql
```

### Run all suites

[](#run-all-suites)

```
./vendor/bin/phpunit
```

### CI

[](#ci)

GitHub Actions runs three jobs in parallel:

JobMatrixServices`unit`PHP 8.2 / 8.3 / 8.4—`integration`PHP 8.2 / 8.3 / 8.4 × MySQL 8.0 / 8.4MySQL service container`integration-pgsql`PHP 8.2 / 8.3 / 8.4 × PostgreSQL 15 / 17PostgreSQL service containerCoverage (Xdebug) is collected on the Unit job for PHP 8.3 and uploaded as a workflow artifact.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance84

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 89.7% 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 ~1 days

Total

6

Last Release

82d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9fec02e3c1d47ecf4251cd03b6486abf8a3250984cb2bc110068ea252d846d10?d=identicon)[ifanfairuz](/maintainers/ifanfairuz)

---

Top Contributors

[![ifanfairuz](https://avatars.githubusercontent.com/u/14147528?v=4)](https://github.com/ifanfairuz "ifanfairuz (26 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (3 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/greatcode-controller-global/health.svg)

```
[![Health](https://phpackages.com/badges/greatcode-controller-global/health.svg)](https://phpackages.com/packages/greatcode-controller-global)
```

###  Alternatives

[google/cloud-core

Google Cloud PHP shared dependency, providing functionality useful to all components.

343121.4M79](/packages/google-cloud-core)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)[ralphjsmit/laravel-helpers

A package containing handy helpers for your Laravel-application.

13704.6k2](/packages/ralphjsmit-laravel-helpers)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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