PHPackages                             rasuvaeff/yii3-ab-testing-db - 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. rasuvaeff/yii3-ab-testing-db

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

rasuvaeff/yii3-ab-testing-db
============================

Database-backed experiment provider for Yii3 A/B testing

v1.1.1(1mo ago)00BSD-3-ClausePHPPHP 8.3 - 8.5CI passing

Since Jun 12Pushed 1w agoCompare

[ Source](https://github.com/rasuvaeff/yii3-ab-testing-db)[ Packagist](https://packagist.org/packages/rasuvaeff/yii3-ab-testing-db)[ Docs](https://github.com/rasuvaeff/yii3-ab-testing-db)[ RSS](/packages/rasuvaeff-yii3-ab-testing-db/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (31)Versions (4)Used By (0)

rasuvaeff/yii3-ab-testing-db
============================

[](#rasuvaeffyii3-ab-testing-db)

[![Stable Version](https://camo.githubusercontent.com/9726343213f756d46e516c42d14cebe2a8aead4d51f4c6c6cab02c2b4c59497e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7261737576616566662f796969332d61622d74657374696e672d64622e7376673f6c6162656c3d737461626c65)](https://packagist.org/packages/rasuvaeff/yii3-ab-testing-db)[![Total Downloads](https://camo.githubusercontent.com/bf614361d90a05a5b18696d05d24d52e315401770ddbedd3ce1d015705bfe023/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7261737576616566662f796969332d61622d74657374696e672d64622e737667)](https://packagist.org/packages/rasuvaeff/yii3-ab-testing-db)[![Build](https://camo.githubusercontent.com/8de2f83bf4d85b892dd260222bd427750d3ff9007572ddae88276ac93688bb7b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7261737576616566662f796969332d61622d74657374696e672d64622f6275696c642e796d6c3f6272616e63683d6d6173746572)](https://github.com/rasuvaeff/yii3-ab-testing-db/actions)[![Static Analysis](https://camo.githubusercontent.com/7d39248b72bf10b1b58dd33c06623f6caa203f6783be9e5c63d7f59b44818292/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7261737576616566662f796969332d61622d74657374696e672d64622f7374617469632d616e616c797369732e796d6c3f6272616e63683d6d6173746572266c6162656c3d737461746963253230616e616c79736973)](https://github.com/rasuvaeff/yii3-ab-testing-db/actions)[![PHP](https://camo.githubusercontent.com/7fc9aa81c07a6d34cbe01bcb3e8234e6cee839d655517b32b151b8776126dbac/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646570656e64656e63792d762f7261737576616566662f796969332d61622d74657374696e672d64622f706870)](https://packagist.org/packages/rasuvaeff/yii3-ab-testing-db)[![License](https://camo.githubusercontent.com/24650c579c63a885a3c64469fb84449276703386b76faf2ba6dfb0706bc6e8ec/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7261737576616566662f796969332d61622d74657374696e672d64622e737667)](LICENSE.md)[Русская версия](README.ru.md)

Database-backed experiment provider for Yii3 A/B testing. Implements the `ExperimentProvider` interface from `rasuvaeff/yii3-ab-testing` and reads experiment configuration from a database table in a single query, so experiments can be toggled and reweighted at runtime without a deploy.

> Using an AI coding assistant? [llms.txt](llms.txt) contains a compact API reference you can ingest in your prompt context.

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

[](#requirements)

- PHP 8.3+
- `rasuvaeff/yii3-ab-testing` ^1.0
- `yiisoft/db` ^2.0
- `yiisoft/db-migration` ^2.0 (ships the table migration)
- a PSR-16 cache implementation — required transitively by `yiisoft/db` 2.0 (e.g. `yiisoft/cache`)

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

[](#installation)

```
composer require rasuvaeff/yii3-ab-testing-db
```

With Yii3 config-plugin this package binds `ExperimentProvider` automatically — do **not** also bind `ExperimentProvider` in your application or another backend, or `yiisoft/config` reports a `Duplicate key` error.

Database schema
---------------

[](#database-schema)

Create the `ab_experiments` table (adjust types for your RDBMS):

```
CREATE TABLE ab_experiments (
    name             VARCHAR(190) PRIMARY KEY,
    enabled          BOOLEAN      NOT NULL DEFAULT TRUE,
    salt             VARCHAR(190) NOT NULL DEFAULT '',
    fallback_variant VARCHAR(190) NOT NULL DEFAULT '',
    variants         TEXT         NOT NULL DEFAULT '{}'
);
```

ColumnTypeDefaultDescription`name``VARCHAR(190)` PK—Experiment name (core regex: `/^[a-z][a-z0-9_-]*$/`)`enabled``BOOLEAN``true`Disabled experiment returns the fallback variant`salt``VARCHAR(190)``''`Empty string falls back to the experiment name`fallback_variant``VARCHAR(190)``''`Must be one of the `variants` keys`variants``JSON`/`TEXT``'{}'`JSON object `{"variant": weight}`, non-negative integer weightsA row's `variants` looks like `{"control":50,"green":50}`. The total weight must be greater than zero and `fallback_variant` must match one of the keys, or the row is rejected with `InvalidExperimentRowException`.

### Migration

[](#migration)

The package ships a migration (`migrations/`) for [yiisoft/db-migration](https://github.com/yiisoft/db-migration). Register the source path in your app's `config/params.php`:

```
'yiisoft/db-migration' => [
    'sourcePaths' => [
        dirname(__DIR__) . '/vendor/rasuvaeff/yii3-ab-testing-db/migrations',
    ],
],
```

Then apply and revert it with Yii Console:

```
./yii migrate:up
./yii migrate:down --limit=1
```

The table name defaults to `ab_experiments` and must match the `table` argument of `DbExperimentProvider`. To use a custom name, bind the migration constructor argument:

```
M260610000000CreateAbExperimentsTable::class => [
    '__construct()' => ['table' => 'my_ab_experiments'],
],
```

Usage
-----

[](#usage)

### Basic DB provider

[](#basic-db-provider)

```
use Rasuvaeff\Yii3AbTesting\AbTesting;
use Rasuvaeff\Yii3AbTesting\WeightedHashAssignmentStrategy;
use Rasuvaeff\Yii3AbTestingDb\DbExperimentProvider;

$provider = new DbExperimentProvider(
    db: $connection,            // yiisoft/db ConnectionInterface
    table: 'ab_experiments',    // optional, default is 'ab_experiments'
);

$ab = new AbTesting(provider: $provider, strategy: new WeightedHashAssignmentStrategy());

if ($ab->is(experiment: 'checkout-button', variant: 'green', subjectId: (string) $userId)) {
    // green variant
}
```

### With PSR-16 caching

[](#with-psr-16-caching)

`getExperiments()` runs on every registry build (per request). Without caching that is a DB query per request — wrap the provider in `CachedExperimentProvider`:

```
use Rasuvaeff\Yii3AbTestingDb\CachedExperimentProvider;

$cached = new CachedExperimentProvider(
    inner: $provider,
    cache: $psr16Cache,         // PSR-16 CacheInterface
    ttl: 60,                    // seconds
);

$ab = new AbTesting(provider: $cached, strategy: new WeightedHashAssignmentStrategy());
```

### Clear cache

[](#clear-cache)

```
$cached->clear();               // removes cached experiments, next call reloads from DB
```

API reference
-------------

[](#api-reference)

ClassDescription`DbExperimentProvider`Reads all experiments from DB in one `SELECT *``CachedExperimentProvider`PSR-16 decorator, caches the entire experiment set with TTL`InvalidExperimentRowException`Thrown when a DB row has invalid structure or yields an invalid experimentSecurity
--------

[](#security)

- Assignment hashing, fallback handling, forced/disabled logic remain in the core package — the DB adapter is only a configuration source.
- Invalid row data (missing columns, malformed `variants` JSON, wrong types, negative weights, invalid experiment name, unknown fallback, zero total weight) throws `InvalidExperimentRowException` instead of silently mis-assigning. Core validation errors are wrapped, so callers only need to catch one exception type.
- No SQL injection risk: the table name is quoted via the yiisoft/db quoter.
- **Reweighting shifts buckets.** Safe to flip `enabled` (kill switch). Changing weights or the variant set shifts bucket boundaries and reshuffles subjects — use `yii3-ab-testing-web` sticky assignment to pin subjects across such changes.

Examples
--------

[](#examples)

See [examples/](examples/) for runnable scripts.

Development
-----------

[](#development)

```
composer build          # full gate: validate + normalize + cs + psalm + test
composer cs:fix         # auto-fix code style
composer psalm          # static analysis
composer test           # run tests
```

License
-------

[](#license)

BSD-3-Clause. See [LICENSE.md](LICENSE.md).

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance96

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

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 ~7 days

Total

3

Last Release

31d ago

### Community

Maintainers

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

---

Top Contributors

[![rasuvaeff](https://avatars.githubusercontent.com/u/1352718?v=4)](https://github.com/rasuvaeff "rasuvaeff (13 commits)")

---

Tags

ab-testingdatabasemigrationsphppsr-16yii-dbyii3databaseproviderdbyii3experimentab-testing

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/rasuvaeff-yii3-ab-testing-db/health.svg)

```
[![Health](https://phpackages.com/badges/rasuvaeff-yii3-ab-testing-db/health.svg)](https://phpackages.com/packages/rasuvaeff-yii3-ab-testing-db)
```

###  Alternatives

[robmorgan/phinx

Phinx makes it ridiculously easy to manage the database migrations for your PHP app.

4.5k48.7M472](/packages/robmorgan-phinx)[masom/lhm

Large Hadron Migrator for phinx

309.5k](/packages/masom-lhm)

PHPackages © 2026

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