Skip to content

Instantly share code, notes, and snippets.

@mavmedved
Created February 7, 2019 15:26
Show Gist options
  • Save mavmedved/effb3f5c1aa38716a735a2f9b92ec462 to your computer and use it in GitHub Desktop.
Save mavmedved/effb3f5c1aa38716a735a2f9b92ec462 to your computer and use it in GitHub Desktop.
<?php
/**
*
* Пошёл по самому простому пути для примера.
*
* Подразумевается, что данный класс будет использоваться только для таблиц с колонкой deleted
* `deleted` tinyint(1) unsigned NOT NULL DEFAULT '0'
*
* пример использования для Customer extends AppActiveRecord:
*
* $customer = Customer::findOne($id);
* $customer->delete();
* $customer->restore();
*
* Customer::deleteAll(['>', 'status', 2]);
* Customer::restoreAll(['>', 'status', 2]);
*
* $customers = Customer::find()->where(['>', 'status', 2])->all();
* foreach ($customers as $customer){
* $customer->delete();
* // $customer->restore();
* }
*
*
*/
namespace app\extended;
use yii\db\ActiveRecord;
class AppActiveRecord extends ActiveRecord
{
/**
* при удалении, всё в конечном итоге сводится к вызову этого метода
* @param null $condition
* @param array $params
* @return bool|int
*/
public static function deleteAll($condition = null, $params = [])
{
if (self::isDeleted($condition, $params)){
return true;
//throw new \yii\base\Exception('Already deleted'); // ну или Exception
// выбрал true, потому что совсем "запрещать" вызов метода может быть не практично
}
return self::updateAll(['deleted' => 1], $condition, $params);
}
/**
* вариант оптимизации:
* кешировать результат функции по conditions в private static $cacheDeleted = [],
* если критичен count в базу и при использовании вызывается к одному и тому же
*
* @param null $condition
* @param array $params
* @return bool
*/
protected static function isDeleted($condition = null, $params = []) : bool
{
$cnt = self::find()
->where($condition)
->params($params)
->count();
$cntDeleted = self::countDeleted($condition, $params);
return $cnt == $cntDeleted ? true : false;
}
/**
* @param null $condition
* @param array $params
* @return int
*/
private static function countDeleted($condition = null, $params = []) : int
{
return (int) self::find()
->where($condition)
->andWhere(['deleted' => 1])
->params($params)
->count();
}
/**
* @return bool|int
*/
public function restore()
{
if ($this->deleted == 0){
return true;
}
$this->deleted = 0;
return $this->update();
}
/**
* @param string|array $condition
* @param array $params
* @return bool|int
*/
public static function restoreAll($condition = '', $params = [])
{
$cntDeleted = self::countDeleted($condition, $params);
if ($cntDeleted == 0){
return true;
}
return self::updateAll(['deleted' => 0], $condition, $params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment