帮酷LOGO

Soft delete behavior for ActiveRecord

ActiveRecord的软删除行为

将光标移到/点击文章中的句子上,可以查看译文。 显示原文      显示译文      双语对照

  • 显示内容
Soft delete behavior for ActiveRecord



  • Source Code:ar-softdelete
  • WebSite:http://www.github.com/yii2tech/ar-softdelete
  • ar-softdelete Documents
  • ar-softdelete Download
  • ActiveRecord Soft Delete Extension for Yii2

    This extension provides support for ActiveRecord soft delete.

    For license information check the LICENSE -file.

    Latest Stable VersionTotal DownloadsBuild Status

    Installation

    The preferred way to install this extension is through composer.

    Either run

    php composer.phar require --prefer-dist yii2tech/ar-softdelete

    or add

    "yii2tech/ar-softdelete": "*"

    to the require section of your composer.json.

    Usage

    This extension provides support for so called"soft"deletion of the ActiveRecord, which means record is not deleted from database, but marked with some flag or status, which indicates it is no longer active, instead.

    This extension provides [[yii2techarsoftdeleteSoftDeleteBehavior] ] ActiveRecord behavior for such solution support in Yii2.you may attach it to your model class in the following way :

    classItemextendsActiveRecord{publicfunctionbehaviors() {return ['softDeleteBehavior'=> ['class'=>SoftDeleteBehavior::className(),'softDeleteAttributeValues'=> ['isDeleted'=>true ], ], ]; }}

    There are 2 ways of"soft"delete applying :

    • using softDelete() separated method
    • mutating regular delete() method

    Usage of softDelete() is recommended, since it allows marking the record as"deleted", while leaving regular delete() method intact, which allows you to perform"hard"delete if necessary.for example :

    $id=17;$item=Item::findOne($id);$item->softDelete(); // mark record as"deleted"$item=Item::findOne($id);var_dump($item->isDeleted); // outputs"true"$item->delete(); // perform actual deleting of the record$item=Item::findOne($id);var_dump($item); // outputs"null"

    However you may want to mutate regular ActiveRecord delete() method in the way in performs"soft"deleting instead of actual removing of the record.it is a common solution in such cases as applying"soft"delete functionality for existing code.for such functionality you should enable [[yii2techarsoftdeleteSoftDeleteBehavior::$replaceRegularDelete] ] option in behavior configuration :

    classItemextendsActiveRecord{publicfunctionbehaviors() {return ['softDeleteBehavior'=> ['class'=>SoftDeleteBehavior::className(),'softDeleteAttributeValues'=> ['isDeleted'=>true ],'replaceRegularDelete'=>true// mutate native `delete()` method ], ]; }}

    Now invocation of the delete() method will mark record as"deleted"instead of removing it :

    $id=17;$item=Item::findOne($id);$item->delete(); // no record removal, mark record as"deleted" instead$item=Item::findOne($id);var_dump($item->isDeleted); // outputs"true"

    Heads up! in case you mutate regular ActiveRecord delete() method, it will be unable to function with ActiveRecord transactions feature, e.g. scenarios with [[yiidbActiveRecord::OP_DELETE] ] or [[yiidbActiveRecord::OP_ALL] ] transaction levels :

    classItemextendsActiveRecord{publicfunctionbehaviors() {return ['softDeleteBehavior'=> ['class'=>SoftDeleteBehavior::className(),'replaceRegularDelete'=>true// mutate native `delete()` method ], ]; }publicfunctiontransactions() {return ['some'=>self::OP_DELETE, ]; }}$item=Item::findOne($id);$item->setScenario('some');$item->delete(); // nothing happens!

    Tip : you may apply a condition, which filters"not deleted"records, to the ActiveQuery as default scope, overriding find() method.also remember, you may reset such default scope using where() method with empty condition.

    classItemextendsActiveRecord{publicfunctionbehaviors() {return ['softDeleteBehavior'=> ['class'=>SoftDeleteBehavior::className(),'softDeleteAttributeValues'=> ['isDeleted'=>true ], ], ]; }publicstaticfunctionfind() {returnparent::find()->where(['isDeleted'=>false]); }}$notDeletedItems=Item::find()->all(); // returns only not"deleted" records$allItems=Item::find()->where([])->all(); // returns all records

    Smart deletion

    Usually"soft"deleting feature is used to prevent the database history loss ensuring data, which been in use and perhaps have a references or dependencies, is kept in the system.however sometimes actual deleting is allowed for such data as well.for example : usually user account records should not be deleted but only marked as"inactive", however if you browse through users list and found accounts, which has been registered long ago, but don't have at least single log-in in the system, these records have no value for the history and can be removed from database to save disk space.

    You can make"soft"deletion to be"smart"and detect, if the record can be removed from database or only marked as"deleted".this can be done via [[yii2techarsoftdeleteSoftDeleteBehavior::$allowDeleteCallback] ].for example :

    classUserextendsActiveRecord{publicfunctionbehaviors() {return ['softDeleteBehavior'=> ['class'=>SoftDeleteBehavior::className(),'softDeleteAttributeValues'=> ['isDeleted'=>true ],'allowDeleteCallback'=>function ($user) {return$user->lastLoginDate===null; // allow delete user, if he has never logged in } ], ]; }}$user=User::find()->where(['lastLoginDate'=>null])->limit(1)->one();$user->softDelete(); // removes the record!!!$user=User::find()->where(['not'=>['lastLoginDate'=>null]])->limit(1)->one();$user->softDelete(); // marks record as"deleted"

    [[yii2techarsoftdeleteSoftDeleteBehavior::$allowDeleteCallback] ] logic is applied in case [[yii2techarsoftdeleteSoftDeleteBehavior::$replaceRegularDelete] ] is enabled as well.

    Handling foreign key constraints

    In case of usage of the relational database, which supports foreign keys, like MySQL, PostgreSQL etc.,"soft"deletion is widely used for keeping foreign keys consistence.for example : if user performs a purchase at the online shop, information about this purchase should remain in the system for the future bookkeeping.the DDL for such data structure may look like following one :

    CREATETABLE `Customer`
    (
     `id`integerNOT NULL AUTO_INCREMENT,
     `name`varchar(64) NOT NULL,
     `address`varchar(64) NOT NULL,
     `phone`varchar(20) NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE InnoDB;CREATETABLE `Purchase`
    (
     `id`integerNOT NULL AUTO_INCREMENT,
     `customerId`integerNOT NULL,
     `itemId`integerNOT NULL,
     `amount`integerNOT NULL,
     PRIMARY KEY (`id`)
     FOREIGN KEY (`customerId`) REFERENCES`Customer` (`id`) ON DELETE RESTRICT ONUPDATE CASCADE,
     FOREIGN KEY (`itemId`) REFERENCES`Item` (`id`) ON DELETE RESTRICT ONUPDATE CASCADE,
    ) ENGINE InnoDB;

    Thus, while set up a foreign key from 'purchase 'to 'user', 'ON DELETE RESTRICT 'mode is used.so on attempt to delete a user record, which have at least one purchase a database error will occur.However, if user record have no external reference, it can be deleted.

    Usage of [[yii2techarsoftdeleteSoftDeleteBehavior::$allowDeleteCallback] ] for such use case is not very practical.it will require performing extra queries to determine, if external references exist or not, eliminating the benefits of the foreign keys database feature.

    Method [yii2techarsoftdeleteSoftDeleteBehavior::safeDelete()] ] attempts to invoke regular [[yiidbBaseActiveRecord::delete()] ] method, and, if it fails with exception, falls back to [[yii2techarsoftdeleteSoftDeleteBehavior::softDelete()] ].

    // if there is a foreign key reference :$customer=Customer::findOne(15);var_dump(count($customer->purchases)); // outputs;"1"$customer->safeDelete(); // performs"soft" delete!var_dump($customer->isDeleted) // outputs:"true"// if there is NO foreign key reference :$customer=Customer::findOne(53);var_dump(count($customer->purchases)); // outputs;"0"$customer->safeDelete(); // performs actual delete!$customer=Customer::findOne(53);var_dump($customer); // outputs:"null"

    By default safeDelete() method catches [[yiidbIntegrityException] ] exception, which means soft deleting will be performed on foreign constraint violation DB exception.you may specify another exception class here to customize fallback error level.for example : usage of [[Exception] ] will cause soft-delete fallback on any error during regular deleting.

    Record restoration

    At some point you may want to"restore"records, which have been marked as"deleted"in the past.you may use restore() method for this :

    $id=17;$item=Item::findOne($id);$item->softDelete(); // mark record as"deleted"$item=Item::findOne($id);$item->restore(); // restore recordvar_dump($item->isDeleted); // outputs"false"

    By default attribute values, which should be applied for record restoration are automatically detected from [[yii2techarsoftdeleteSoftDeleteBehavior::$softDeleteAttributeValues] ], however it is better you specify them explicitly via [[yii2techarsoftdeleteSoftDeleteBehavior::$restoreAttributeValues] ].

    Events

    By default [[yii2techarsoftdeleteSoftDeleteBehavior::softDelete()] ] triggers [[yiidbBaseActiveRecord::EVENT_BEFORE_DELETE] ] and [[yiidbBaseActiveRecord::EVENT_AFTER_DELETE] ] events in the same way they are triggered at regular delete().

    Also [[yii2techarsoftdeleteSoftDeleteBehavior] ] triggers several additional events in the scope of the owner ActiveRecord :

    • [[yii2techarsoftdeleteSoftDeleteBehavior::EVENT_BEFORE_SOFT_DELETE] ] - triggered before"soft"delete is made.
    • [[yii2techarsoftdeleteSoftDeleteBehavior::EVENT_AFTER_SOFT_DELETE] ] - triggered after"soft"delete is made.
    • [[yii2techarsoftdeleteSoftDeleteBehavior::EVENT_BEFORE_RESTORE] ] - triggered before record is restored from"deleted"state.
    • [[yii2techarsoftdeleteSoftDeleteBehavior::EVENT_AFTER_RESTORE] ] - triggered after record is restored from"deleted"state.

    You may attach the event handlers for these events to your ActiveRecord object :

    $item=Item::findOne($id);$item->on(SoftDeleteBehavior::EVENT_BEFORE_SOFT_DELETE, function($event) {$event->isValid=false; // prevent"soft" delete to be performed});

    You may also handle these events inside your ActiveRecord class by declaring the corresponding methods :

    classItemextendsActiveRecord{publicfunctionbehaviors() {return ['softDeleteBehavior'=> ['class'=>SoftDeleteBehavior::className(),//.. . ], ]; }publicfunctionbeforeSoftDelete() {$this->deletedAt=time(); // log the deletion datereturntrue; }publicfunctionbeforeRestore() {return$this->deletedAt> (time() -3600); // allow restoration only for the records, being deleted during last hour }}



    Copyright © 2011 HelpLib All rights reserved.    知识分享协议 京ICP备05059198号-3  |  如果智培  |  酷兔英语