我在 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;
}
如果我使用特征,SoftDeleteTrait 就会以真实的方式工作。但 SoftDeleteBehavior 无法正常工作!
最佳答案
一个是 PHP 语言构造,另一个是编程概念。您可能想要read upon what traits are ,这样你就明白这个问题就目前而言并没有多大意义。另外,诸如“不起作用”之类的内容并不能作为正确的问题描述,请在以后更加具体。
话虽这么说,CakePHP 行为确实服务于水平代码重用,类似于特征,而不是通过继承进行垂直重用。
然而,即使它们在概念上有相似之处,你也不能像在代码中那样简单地交换它们,一个特征将被复合到使用它的类中,这样它就成为它的一部分,就好像它一样直接编写在类定义中,因此能够覆盖继承的代码,例如 Table::_processDelete()
方法,另一方面,行为是一个完全独立的类,正在实例化并在运行时作为依赖项注入(inject)到表类中,并且通过表类委托(delegate)对其方法的调用(请参阅 Table::__call() ),除非已存在同名的方法在表类上,在您的情况下这意味着 _processDelete()
将永远不会被调用。
我建议您多学习一点 PHP/OOP 基础知识,因为这是相当基本的东西,只需查看源代码就可以轻松解决。能够理解 CakePHP 代码库和所使用的概念如何工作将使您的生活变得更加轻松。
关于behavior - cakephp 3 中的特征和行为有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409904/