mspirkov/yii2-db 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mspirkov/yii2-db

Composer 安装命令:

composer require mspirkov/yii2-db

包简介

Yii2 DB extension.

README 文档

README

Yii2 DB Extension

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

PHP Yii 2.0.x Tests PHPStan Coverage PHPStan Level Max

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

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

Create an interface based on RepositoryInterface:

use MSpirkov\Yii2\Db\ActiveRecord\RepositoryInterface;

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

Next, create your repository:

use MSpirkov\Yii2\Db\ActiveRecord\AbstractRepository;

/**
 * @extends AbstractRepository<Product>
 */
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

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

Usage example

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

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

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
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;
    }
}

mspirkov/yii2-db 适用场景与选型建议

mspirkov/yii2-db 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 82 次下载、GitHub Stars 达 3, 最近一次更新时间为 2025 年 10 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「db」 「Active Record」 「yii」 「yii2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mspirkov/yii2-db 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mspirkov/yii2-db 我们能提供哪些服务?
定制开发 / 二次开发

基于 mspirkov/yii2-db 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 82
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 7
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-24