mspirkov/yii2-db Yii2 DB extension.
Yii2 DB
A package of helper classes for working with databases in Yii2.
Installation¶
Run
php composer.phar require mspirkov/yii2-dbor add
"mspirkov/yii2-db":"^0.1"to therequire section of yourcomposer.json file.
Components¶
AbstractRepository¶
An abstract class for creating repositories that interact with ActiveRecord models. Contains the most commonly used methods:findOne,findAll,save and others. It also has several additional methods:findOneWith,findAllWith.
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:¶
/** *@extends AbstractRepository<Customer> */classCustomerRepositoryextendsAbstractRepository{publicfunction__construct(){parent::__construct(Customer::class); }}classCustomerService{publicfunction__construct( private readonly CustomerRepository $customerRepository, ){}publicfunctiongetCustomer(int $id): ?Customer{return$this->customerRepository->findOne($id); }}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:¶
classTransactionManagerextends \MSpirkov\Yii2\Db\TransactionManager{publicfunction__construct(){parent::__construct(Yii::$app->db); }}classProductService{publicfunction__construct( private readonly TransactionManager $transactionManager, private readonly ProductFilesystem $productFilesystem, private readonly ProductRepository $productRepository, ){}/** *@return array{success: bool, message?: string} */publicfunctiondeleteProduct(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->productFilesystem->delete($product->preview_filename);return ['success' =>true, ]; });if ($transactionResult ===false) {return ['success' =>false,'message' =>'Something went wrong', ]; }return $transactionResult; }}Github Repository