PHPackages                             mspirkov/yii2-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. mspirkov/yii2-db

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

mspirkov/yii2-db
================

Yii2 DB extension.

0.3.1(1mo ago)376MITPHPPHP &gt;=7.4CI passing

Since Oct 25Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/mspirkov/yii2-db)[ Packagist](https://packagist.org/packages/mspirkov/yii2-db)[ RSS](/packages/mspirkov-yii2-db/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)Dependencies (19)Versions (10)Used By (0)

 [ ![](https://avatars0.githubusercontent.com/u/993323) ](https://github.com/yiisoft)

Yii2 DB Extension
=================

[](#yii2-db-extension)

A package of helper classes for working with databases in Yii2.

[![PHP](https://camo.githubusercontent.com/de6657ab22d88fd2e8c1fda7dbffa5716c7d53ea6250959be771ea72d4863315/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f253345253344372e342d3741383642382e7376673f7374796c653d666f722d7468652d6261646765266c6f676f3d706870266c6f676f436f6c6f723d7768697465266c6162656c3d504850)](https://www.php.net/releases/7_4_0.php)[![Yii 2.0.x](https://camo.githubusercontent.com/a8b86019a796c90e714cf9d9b730c74f7c01dfef6f1704e928cb1d991fad0065/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f253345253344322e302e35332d3234374241302e7376673f7374796c653d666f722d7468652d6261646765266c6f676f3d796969266c6f676f436f6c6f723d7768697465266c6162656c3d596969)](https://github.com/yiisoft/yii2/tree/2.0.53)[![Tests](https://camo.githubusercontent.com/256cc69e9962956f10d92fbb02ddd03d132511b7bea0f0de82c231c55d5bd461/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d737069726b6f762f796969322d64622f63692e796d6c3f6272616e63683d6d61696e267374796c653d666f722d7468652d6261646765266c6f676f3d676974687562266c6162656c3d5465737473)](https://github.com/mspirkov/yii2-db/actions/workflows/ci.yml)[![PHPStan](https://camo.githubusercontent.com/57d1ab34d506f1d1c43df838f41058654f0d70480593ce71ac4294090412868a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d737069726b6f762f796969322d64622f63692e796d6c3f6272616e63683d6d61696e267374796c653d666f722d7468652d6261646765266c6f676f3d676974687562266c6162656c3d5048505374616e)](https://github.com/mspirkov/yii2-db/actions/workflows/ci.yml)[![Coverage](https://camo.githubusercontent.com/6ec077aa0bac0ac481f0e07cfdcb41ab11064cea82be02d7fb6f17027f9161b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f3130302532352d3434434331312e7376673f7374796c653d666f722d7468652d6261646765266c6162656c3d436f766572616765)](https://camo.githubusercontent.com/6ec077aa0bac0ac481f0e07cfdcb41ab11064cea82be02d7fb6f17027f9161b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f3130302532352d3434434331312e7376673f7374796c653d666f722d7468652d6261646765266c6162656c3d436f766572616765)[![PHPStan Level Max](https://camo.githubusercontent.com/347927812a31a0b0090fefb12765bc416adeb9383f8accf29740e8ffcdd43836/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4d61782d3741383642382e7376673f7374796c653d666f722d7468652d6261646765266c6162656c3d5048505374616e2532304c6576656c)](https://camo.githubusercontent.com/347927812a31a0b0090fefb12765bc416adeb9383f8accf29740e8ffcdd43836/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4d61782d3741383642382e7376673f7374796c653d666f722d7468652d6261646765266c6162656c3d5048505374616e2532304c6576656c)

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

[](#installation)

Run

```
php composer.phar require mspirkov/yii2-db
```

or add

```
"mspirkov/yii2-db": "^0.3"
```

to the `require` section of your `composer.json` file.

Components
----------

[](#components)

- [AbstractRepository](#abstractrepository)
- [DateTimeBehavior](#datetimebehavior)
- [TransactionManager](#transactionmanager)

### AbstractRepository

[](#abstractrepository)

An abstract class for creating repositories that interact with ActiveRecord models.

Contains the most commonly used methods:

- `findOne` - finds a single ActiveRecord model based on the provided condition.
- `findAll` - finds all ActiveRecord models based on the provided condition.
- `save` - saves an ActiveRecord model to the database.
- `delete` - deletes an ActiveRecord model from the database.
- `updateAll` - updates the whole table using the provided attribute values and conditions.
- `deleteAll` - deletes rows in the table using the provided conditions.

It also has several additional methods:

- `findOneWith` - finds a single ActiveRecord model based on the provided condition and eager loads the specified relations.
- `findAllWith` - finds all ActiveRecord models based on the provided condition and eager loads the specified relations.
- `getTableSchema` - returns the schema information of the DB table associated with current ActiveRecord class.
- `find` - creates and returns a new ActiveQuery instance for the current ActiveRecord model.

This way, you can separate the logic of executing queries from the ActiveRecord models themselves. This will make your ActiveRecord models thinner and simpler. It will also make testing easier, as you can mock the methods for working with the database.

#### Usage example

[](#usage-example)

Create an interface based on `RepositoryInterface`:

```
use MSpirkov\Yii2\Db\ActiveRecord\RepositoryInterface;

/**
 * @extends RepositoryInterface
 */
interface ProductRepositoryInterface extends RepositoryInterface
{
    /**
     * @return Product[]
     */
    public function findForMainPage(int $limit): array
}
```

Next, create your repository:

```
use MSpirkov\Yii2\Db\ActiveRecord\AbstractRepository;

/**
 * @extends AbstractRepository
 */
final class ProductRepository extends AbstractRepository implements ProductRepositoryInterface
{
    public function __construct()
    {
        parent::__construct(Product::class);
    }

    public function findForMainPage(int $limit): array
    {
        return $this->find()
            ->where(['hidden' => 0])
            ->orderBy(['id' => SORT_DESC])
            ->limit($limit)
            ->all();
    }
}
```

After that, specify the implementation of the `ProductRepositoryInterface` interface in the container in the `definitions` section:

```
return [
    ...
    'container' => [
        'definitions' => [
            ProductRepositoryInterface::class => ProductRepository::class,
        ],
    ],
    ...
];
```

After that, you can use the repository as follows:

```
final readonly class MainService
{
    private const int PRODUCTS_LIMIT = 20;

    public function __construct(
        private ProductRepositoryInterface $productRepository,
    ) {}

    /**
     * @return array{
     *     products: Product[],
     * }
     */
    public function getMainData(int $id): array
    {
        $products = $this->productRepository->findForMainPage(self::PRODUCTS_LIMIT);

        return [
            'products' => $products,
        ];
    }
}
```

### DateTimeBehavior

[](#datetimebehavior)

Behavior for ActiveRecord models that automatically fills the specified attributes with the current date and time.

#### Usage example

[](#usage-example-1)

```
use MSpirkov\Yii2\Db\ActiveRecord\DateTimeBehavior;

/**
 * @property int $id
 * @property string $content
 * @property string $created_at
 * @property string|null $updated_at
 */
final class Message extends ActiveRecord
{
    public static function tableName(): string
    {
        return '{{messages}}';
    }

    public function behaviors(): array
    {
        return [
            DateTimeBehavior::class,
        ];
    }
}
```

By default, this behavior will fill the `created_at` attribute with the date and time when the associated AR object is being inserted; it will fill the `updated_at` attribute with the date and time when the AR object is being updated. The date and time are determined relative to `$timeZone`.

If your attribute names are different or you want to use a different way of calculating the timestamp, you may configure the `$createdAtAttribute`, `$updatedAtAttribute` and `$value` properties like the following:

```
use MSpirkov\Yii2\Db\ActiveRecord\DateTimeBehavior;
use yii\db\Expression;

/**
 * @property int $id
 * @property string $content
 * @property string $create_time
 * @property string|null $update_time
 */
final class Message extends ActiveRecord
{
    public static function tableName(): string
    {
        return '{{messages}}';
    }

    public function behaviors(): array
    {
        return [
            [
                'class' => DateTimeBehavior::class,
                'createdAtAttribute' => 'create_time',
                'updatedAtAttribute' => 'update_time',
                'value' => new Expression('NOW()'),
            ],
        ];
    }
}
```

### TransactionManager

[](#transactionmanager)

A utility class for managing database transactions with a consistent and safe approach.

This class simplifies the process of wrapping database operations within transactions, ensuring that changes are either fully committed or completely rolled back in case of errors.

It provides two main methods:

- `safeWrap` - executes a callable within a transaction, safely handling exceptions and logging them.
- `wrap` - executes a callable within a transaction.

#### Usage example

[](#usage-example-2)

##### Initialization

[](#initialization)

Add the definition to the `container` configuration in the `definitions` section:

```
use MSpirkov\Yii2\Db\TransactionManagerInterface;
use MSpirkov\Yii2\Db\TransactionManager;

return [
    ...
    'container' => [
        'definitions' => [
            TransactionManagerInterface::class => static fn() => new TransactionManager(Yii::$app->db),
        ],
    ],
    ...
];
```

##### Usage

[](#usage)

```
use MSpirkov\Yii2\Db\TransactionManagerInterface;

final readonly class ProductService
{
    public function __construct(
        private TransactionManagerInterface $transactionManager,
        private FilesystemInterface $filesystem,
        private ProductRepositoryInterface $productRepository,
    ) {}

    /**
     * @return array{success: bool, message?: string}
     */
    public function deleteProduct(int $id): array
    {
        $product = $this->productRepository->findOne($id);

        // There's some logic here. For example, checking for the existence of a product.

        $transactionResult = $this->transactionManager->safeWrap(function () use ($product) {
            $this->productRepository->delete($product);
            $this->filesystem->delete($product->file_path);

            return [
                'success' => true,
            ];
        });

        if ($transactionResult === false) {
            return [
                'success' => false,
                'message' => 'Something went wrong',
            ];
        }

        return $transactionResult;
    }
}
```

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance89

Actively maintained with recent releases

Popularity15

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity31

Early-stage or recently created project

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

Total

9

Last Release

59d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/45cacb752e41df997e47ec498acabbc548e07ae1c82d2d1a9a0f468c37e52a8e?d=identicon)[mspirkov](/maintainers/mspirkov)

---

Top Contributors

[![mspirkov](https://avatars.githubusercontent.com/u/63721828?v=4)](https://github.com/mspirkov "mspirkov (63 commits)")

---

Tags

active-recorddatabasephpphp7php8transactionsyiiyii2yii2-extensiondbyii2active-recordyii

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mspirkov-yii2-db/health.svg)

```
[![Health](https://phpackages.com/badges/mspirkov-yii2-db/health.svg)](https://phpackages.com/packages/mspirkov-yii2-db)
```

###  Alternatives

[voskobovich/yii2-linker-behavior

This behavior makes it easy to maintain many-to-many and one-to-many relations in your ActiveRecord models.

80319.0k9](/packages/voskobovich-yii2-linker-behavior)[sjaakp/yii2-spatial

Yii2 ActiveRecord supporting MySQL spatial data

1873.8k1](/packages/sjaakp-yii2-spatial)[mg-code/yii2-helpers

A collection of useful helper classes for Yii framework 2.0

2022.5k5](/packages/mg-code-yii2-helpers)[dmstr/yii2-db

Database extensions

19618.8k6](/packages/dmstr-yii2-db)[arogachev/yii2-tree

Database tree structures management for Yii 2 framework

222.1k](/packages/arogachev-yii2-tree)

PHPackages © 2026

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