mspirkov / yii2-db
Yii2 DB extension.
Installs: 11
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/mspirkov/yii2-db
Requires
- php: >=7.4
- yiisoft/yii2: ^2.0.53
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.89
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^9.6
- rector/rector: ^2.2
README
A package of helper classes for working with databases in Yii2.
Installation
Run
php composer.phar require mspirkov/yii2-db
or add
"mspirkov/yii2-db": "^0.1"
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, 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> */ class CustomerRepository extends AbstractRepository { public function __construct() { parent::__construct(Customer::class); } }
class CustomerService { public function __construct( private readonly CustomerRepository $customerRepository, ) {} public function getCustomer(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:
class DbTransactionManager extends TransactionManager { public function __construct() { parent::__construct(Yii::$app->db); } }
class ProductService { public function __construct( private readonly DbTransactionManager $dbTransactionManager, private readonly ProductFilesystem $productFilesystem, private readonly ProductRepository $productRepository, ) {} /** * @return array{success: bool, message?: string} */ public function deleteProduct(int $id): array { $product = $this->productRepository->findOne($id); // Checks before performing the deletion $transactionResult = $this->dbTransactionManager->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; } }