PHP 实现SoftDelete 软删除

我们在用Laravel开发项目时常会用到软删除的功能,此篇文章将用Yii来实现相同的功能。
实现方式是基于Yii特性Behavior来实现,首先建立一个SoftDeleteBehavior 的行为,如下:

<?php
/**
 * IB - SoftDelete - do as Laravel
 * User: Great Nomandia
 * Date: 2018/12/3 23:38
 */

class SoftDeleteBehavior extends CActiveRecordBehavior
{
    /**
     * @var string 删除时间字段
     */
    public $deletedAttribute = 'deleted_at';

    /**
     * @var string 删除状态字段
     */
    public $deletedStateAttribute = 'state';

    /**
     * @var int 删除状态值
     */
    public $deletedStateValue = 9;

    /**
     * @var string
     */
    public $timestampExpression;
    /**
     * @var array 映射数据库(MySQL)字段类型对应的默认值
     */
    protected static $map = array(
        'datetime' => 'NOW()',
        'timestamp' => 'NOW()',
        'date' => 'NOW()',
        'int' => 'UNIX_TIMESTAMP()',
    );

    /**
     * @param CEvent $event
     * @return bool
     * @throws CException
     * Author Nomandia
     * Created At 2018/12/3 23:48
     */
    function beforeDelete($event)
    {
        if ($this->getOwner()) {
            if (null !== $this->deletedAttribute ) {
                // 这里设置删除时间字段
                $this->getOwner()->{$this->deletedAttribute} = $this->getTimestampByAttribute($this->deletedAttribute);
            }
            if (null !== $this->deletedStateAttribute ) {
                $this->getOwner()->{$this->deletedStateAttribute} = $this->deletedStateValue;
            }
            $this->getOwner()->update([$this->deletedStateAttribute, $this->deletedAttribute]);

            $event->isValid = false; // 注意这需要设置false以阻止删除行为执行,true则表示实际删除
            return false;
        }
    }


    /**
     * 获取删除字段对应的列默认值
     *
     * @param string $attribute $attribute
     * @return mixed timestamp (eg unix timestamp or a mysql function)
     */
    protected function getTimestampByAttribute($attribute)
    {
        if ($this->timestampExpression instanceof CDbExpression)
            return $this->timestampExpression;
        elseif ($this->timestampExpression !== null) {
            try {
                return @eval('return ' . $this->timestampExpression . ';');
            } catch (ParseError $e) {
                return false;
            }
        }

        $columnType = $this->getOwner()->getTableSchema()->getColumn($attribute)->dbType;
        return $this->getTimestampByColumnType($columnType);
    }

    /**
     * 返回列类型
     *
     * @param string $columnType $columnType
     * @return mixed timestamp (eg unix timestamp or a mysql function)
     */
    protected function getTimestampByColumnType($columnType)
    {
        return isset(self::$map[$columnType]) ? new CDbExpression(self::$map[$columnType]) : time();
    }
}

使用起来也很简单

class User extends CActiveRecord{
// other codes
    function behaviors()
    {
        return array_merge([
            ['class' => 'SoftDeleteBehavior', 'deletedStateAttribute' => null], // 关闭了state更新
        ], parent::behaviors());
    }
// other codes
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • PHP学习线路图 PHP教程 PHP教程PHP简介PHP环境设置PHP语法概述PHP变量类型PHP常量类型 PHP...
    茶茶点阅读 780评论 1 4
  • 过去做事情急,什么东西拿起来就用,不喜欢进行系统性的学习,造成在使用过程中的错误和低效,现在感觉自己耐心多了,用之...
    马文Marvin阅读 2,022评论 0 10
  • date: 2017-11-21 18:15:18title: yii 源码解读 百度脑图 - yii 源码解析:...
    daydaygo阅读 3,504评论 1 11
  • 对于 Web 开发者来说,PHP 是一款非常强大而又受欢迎的编程语言。世界上很多顶级的网站都是基于 PHP 开发的...
    chansey阅读 1,154评论 2 0
  • 为什么Laravel会脱颖而出 在动态Web开发的早期,编写一个Web应用看起来是非常不同和当今相比。开发者们不仅...
    如来神掌阅读 3,252评论 1 3