Yii2Tech ar-softdelete 项目使用教程
1. 项目目录结构及介绍
Yii2Tech ar-softdelete 是一个为 Yii2 框架提供的软删除扩展。以下是项目的目录结构及其介绍:
yii2tech/ar-softdelete/
├── .gitattributes
├── .gitignore
├── .travis.yml
├── CHANGELOG.md
├── LICENSE.md
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│ ├── base/
│ │ └── SoftDeleteBehavior.php
│ └── SoftDeleteQueryBehavior.php
└── tests/
├── acceptance/
├── functional/
└── unit/
src/
目录包含扩展的核心代码。tests/
目录包含单元测试、功能测试和验收测试。.gitattributes
、.gitignore
、.travis.yml
、composer.json
、phpunit.xml.dist
等文件是项目配置文件和自动化测试配置。
2. 项目的启动文件介绍
Yii2Tech ar-softdelete 扩展的启动非常简单。首先,你需要通过 Composer 安装扩展:
php composer.phar require --prefer-dist yii2tech/ar-softdelete
或者在你的 composer.json
文件中添加以下依赖:
{
"require": {
"yii2tech/ar-softdelete": "*"
}
}
安装完毕后,你需要在你的 ActiveRecord 模型中添加 SoftDeleteBehavior
行为。例如:
use yii\db\ActiveRecord;
use yii2tech\ar\softdelete\SoftDeleteBehavior;
class Item extends ActiveRecord
{
public function behaviors()
{
return [
'softDeleteBehavior' => [
'class' => SoftDeleteBehavior::className(),
'softDeleteAttributeValues' => [
'isDeleted' => true
],
],
];
}
}
3. 项目的配置文件介绍
Yii2Tech ar-softdelete 扩展的配置主要集中在行为配置上。以下是一个配置 SoftDeleteBehavior
的示例:
public function behaviors()
{
return [
'softDeleteBehavior' => [
'class' => SoftDeleteBehavior::className(),
'softDeleteAttributeValues' => [
'isDeleted' => true
],
'replaceRegularDelete' => true, // 可选,如果你想要覆盖默认的 delete() 方法
],
];
}
在这里,softDeleteAttributeValues
选项用于指定哪些属性值表示记录已被软删除。replaceRegularDelete
选项允许你决定是否覆盖 ActiveRecord 的 delete()
方法以执行软删除。
此外,如果你想要在查询时过滤软删除的记录,你可以在查询时附加 SoftDeleteQueryBehavior
:
public static function find()
{
$query = parent::find();
$query->attachBehavior('softDelete', SoftDeleteQueryBehavior::className());
return $query;
}
这样配置后,你就可以使用 find()
方法提供的 deleted()
和 notDeleted()
范围来过滤查询结果了。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考