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.2"
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: ΒΆ
use MSpirkov\Yii2\Db\ActiveRecord\AbstractRepository;
/**
* @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);
}
}
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
*/
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
*/
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: ΒΆ
class TransactionManager extends \MSpirkov\Yii2\Db\TransactionManager
{
public function __construct()
{
parent::__construct(Yii::$app->db);
}
}
class ProductService
{
public function __construct(
private readonly TransactionManager $transactionManager,
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);
// 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;
}
}
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.