PHP code example of yii2dev / ar-softdelete

1. Go to this page and download the library: Download yii2dev/ar-softdelete library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yii2dev / ar-softdelete example snippets




use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;

class Item extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                'softDeleteAttributeValues' => [
                    'isDeleted' => true
                ],
            ],
        ];
    }
}



$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"



use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;

class Item extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                'softDeleteAttributeValues' => [
                    'isDeleted' => true
                ],
                'replaceRegularDelete' => true // mutate native `delete()` method
            ],
        ];
    }
}



$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"



use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;

class Item extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                'replaceRegularDelete' => true // mutate native `delete()` method
            ],
        ];
    }

    public function transactions()
    {
        return [
            'some' => self::OP_DELETE,
        ];
    }
}

$item = Item::findOne($id);
$item->setScenario('some');
$item->delete(); // nothing happens!



// returns only not "deleted" records
$notDeletedItems = Item::find()
    ->where(['isDeleted' => false])
    ->all();

// returns "deleted" records
$deletedItems = Item::find()
    ->where(['isDeleted' => true])
    ->all();



use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;
use yii2dev\ar\softdelete\SoftDeleteQueryBehavior;

class Item extends ActiveRecord
{
    // ...
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                // ...
            ],
        ];
    }

    /**
     * @return \yii\db\ActiveQuery|SoftDeleteQueryBehavior
     */
    public static function find()
    {
        $query = parent::find();
        $query->attachBehavior('softDelete', SoftDeleteQueryBehavior::class);
        return $query;
    }
}



use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;
use yii2dev\ar\softdelete\SoftDeleteQueryBehavior;

class Item extends ActiveRecord
{
    // ...
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                // ...
            ],
        ];
    }

    /**
     * @return ItemQuery|SoftDeleteQueryBehavior
     */
    public static function find()
    {
        return new ItemQuery(get_called_class());
    }
}

class ItemQuery extends \yii\db\ActiveQuery
{
    public function behaviors()
    {
        return [
            'softDelete' => [
                'class' => SoftDeleteQueryBehavior::class,
            ],
        ];
    }
}



// Find all "deleted" records:
$deletedItems = Item::find()->deleted()->all();

// Find all "active" records:
$notDeletedItems = Item::find()->notDeleted()->all();

// find all comments for not "deleted" items:
$comments = Comment::find()
    ->innerJoinWith(['item' => function ($query) {
        $query->notDeleted();
    }])
    ->all();



// Filter records by "soft" deleted criteria:
$items = Item::find()
    ->filterDeleted(Yii::$app->request->get('filter_deleted'))
    ->all();



use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;
use yii2dev\ar\softdelete\SoftDeleteQueryBehavior;

class Item extends ActiveRecord
{
    // ...
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                'softDeleteAttributeValues' => [
                    'statusId' => 'deleted',
                ],
            ],
        ];
    }

    /**
     * @return \yii\db\ActiveQuery|SoftDeleteQueryBehavior
     */
    public static function find()
    {
        $query = parent::find();
        
        $query->attachBehavior('softDelete', [
            'class' => SoftDeleteQueryBehavior::class,
            'deletedCondition' => [
                'statusId' => 'deleted',
            ],
            'notDeletedCondition' => [
                'statusId' => 'active',
            ],
        ]);
        
        return $query;
    }
}



use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;
use yii2dev\ar\softdelete\SoftDeleteQueryBehavior;

class Item extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                'softDeleteAttributeValues' => [
                    'isDeleted' => true
                ],
            ],
        ];
    }

    /**
     * @return \yii\db\ActiveQuery|SoftDeleteQueryBehavior
     */
    public static function find()
    {
        $query = parent::find();
        
        $query->attachBehavior('softDelete', SoftDeleteQueryBehavior::class);
        
        return $query->notDeleted();
    }
}

$notDeletedItems = Item::find()->all(); // returns only not "deleted" records

$allItems = Item::find()
    ->onCondition([]) // resets "not deleted" scope for relational databases
    ->all(); // returns all records

$allItems = Item::find()
    ->where([]) // resets "not deleted" scope for NOSQL databases
    ->all(); // returns all records


 
use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;

class User extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                '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"



// 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"



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

$item = Item::findOne($id);
$item->restore(); // restore record
var_dump($item->isDeleted); // outputs "false"



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



use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;

class Item extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::class,
                // ...
            ],
        ];
    }

    public function beforeSoftDelete()
    {
        $this->deletedAt = time(); // log the deletion date
        return true;
    }

    public function beforeRestore()
    {
        return $this->deletedAt > (time() - 3600); // allow restoration only for the records, being deleted during last hour
    }
}



$item = Item::findOne($id);

$transaction = $item->getDb()->beginTransaction();
try {
    $item->softDelete();
    // ...other DB operations...
    $transaction->commit();
} catch (\Exception $e) { // PHP < 7.0
    $transaction->rollBack();
    throw $e;
} catch (\Throwable $e) { // PHP >= 7.0
    $transaction->rollBack();
    throw $e;
}



use yii\db\ActiveRecord;
use yii2dev\ar\softdelete\SoftDeleteBehavior;

class Item extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'softDelete' => [
                'class' => SoftDeleteBehavior::class,
                'softDeleteAttributeValues' => [
                    'isDeleted' => true
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function optimisticLock()
    {
        return 'version';
    }
}


use yii\helpers\Html;

/* @var $model Item */



use yii\db\StaleObjectException;
use yii\web\Controller;

class ItemController extends Controller
{
    public function delete($id, $version)
    {
        $model = $this->findModel($id);
        $model->version = $version;
        
        try {
            $model->softDelete();
            return $this->redirect(['index']);
        } catch (StaleObjectException $e) {
            // logic to resolve the conflict
        }
    }
    
    // ...
}