我发现在通过特性实现的cakephp 3中实现了软删除。我尝试通过行为来实现它。但是与特征版本不同,SoftDeleteBehavior不起作用。我的模型初始化方法中有以下代码行:
$this->addBehavior('SoftDelete');
这是我的SoftDeleteBehavior
namespace App\Model\Behavior;
use Cake\ORM\Behavior;
use Cake\ORM\RulesChecker;
use Cake\Datasource\EntityInterface;
use App\Model\Behavior\MyQuery;
class SoftDeleteBehavior extends Behavior {
public $user_id = 1;
public function getDeleteDate() {
return isset($this->deleteDate) ? $this->deleteDate : 'deleted';
}
public function getDeleter() {
return isset($this->deleter) ? $this->deleter : 'deleter_id';
}
public function query() {
return new MyQuery($this->connection(), $this);
}
/**
* Perform the delete operation.
*
* Will soft delete the entity provided. Will remove rows from any
* dependent associations, and clear out join tables for BelongsToMany associations.
*
* @param \Cake\DataSource\EntityInterface $entity The entity to soft delete.
* @param \ArrayObject $options The options for the delete.
* @throws \InvalidArgumentException if there are no primary key values of the
* passed entity
* @return bool success
*/
protected function _processDelete($entity, $options) {
if ($entity->isNew()) {
return false;
}
$primaryKey = (array)$this->primaryKey();
if (!$entity->has($primaryKey)) {
$msg = 'Deleting requires all primary key values.';
throw new \InvalidArgumentException($msg);
}
if (isset($options['checkRules']) && !$this->checkRules($entity, RulesChecker::DELETE, $options)) {
return false;
}
$event = $this->dispatchEvent('Model.beforeDelete', [
'entity' => $entity,
'options' => $options
]);
if ($event->isStopped()) {
return $event->result;
}
$this->_associations->cascadeDelete(
$entity,
['_primary' => false] + $options->getArrayCopy()
);
$query = $this->query();
$conditions = (array)$entity->extract($primaryKey);
$statement = $query->update()
->set([$this->getDeleteDate() => date('Y-m-d H:i:s') , $this->getDeleter() => $this->user_id])
->where($conditions)
->execute();
$success = $statement->rowCount() > 0;
if (!$success) {
return $success;
}
$this->dispatchEvent('Model.afterDelete', [
'entity' => $entity,
'options' => $options
]);
return $success;
}
如果我使用trait,SoftDeleteTrait会以真实的方式工作。但是SoftDeleteBehavior无法正常工作!
一种是PHP语言构造,另一种是编程概念。您可能想读一下特质是什么,以便您理解这个问题,就目前而言,没有太大意义。此外,“不起作用”之类的内容也不能作为正确的问题描述,请在将来进行更具体的说明。
话虽这么说,CakePHP行为确实达到了类似于特质的水平代码重用的目的,而不是通过继承实现了垂直重用。
但是,即使它们具有概念上的相似性,您也不能像在代码中那样简单地交换它们,一个特征将被组合到使用它的类中,从而使其像直接编写一样成为它的一部分。在类定义中,因此具有覆盖Table::_processDelete()
方法之类的继承代码的能力,另一方面,行为是一个完全独立的类,在运行时实例化该类并将其作为依赖项注入到表类中,并对其进行调用方法是通过表类委托的(请参阅参考资料Table::__call()
),除非表类上已经存在具有相同名称的方法,这对您而言意味着_processDelete()
永远不会被调用。
我建议您学习更多有关PHP / OOP基础知识,因为这是相当基础的内容,只需查看源代码即可轻松弄清。能够了解CakePHP代码库和所用概念的工作原理将使您的生活变得更加轻松。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句