Yii2 DB Extension
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.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;
}
}
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.