Laravel: 不变的特质

Laravel: immutable Trait

我需要当文档被视为关闭时,您将无法再修改、更新或删除它。

我正在考虑使用像“ImmutableTrait”这样的特征。 我已经这样做了:

<?php

namespace App\Traits;
use Illuminate\Database\Eloquent\Model;

trait ImmutableTrait
{
 protected $isImmutable = false;

 public function setAttribute($key, $value)
 {
     if ($this->isImmutable) {
        return $this;
 }

  return parent::setAttribute($key, $value);
 }
}

然后在我的模型中:


use Illuminate\Database\Eloquent\Model;
use App\Traits\ImmutableTrait;

class MedicalRecord extends Model
{
 use ImmutableTrait;


 public function closeDocument()
 {
    $this->isImmutable = true;
 }
}

最后是控制器:


public function closeDocument(Document $document)
{
    .....
    $document->closeDocument();
    $document->saveorfail();
}

然后,如果我尝试检索封闭模型并更新字段,我应该无法做到:


Route::put('{document}/updateStatus', 'DocumentController@updateStatus');


class DocumentController extends Controller
{
  ....
  public function updateStatus(Document $document)
  {
    $document->status= "TEST";
    $document->saveorfail();
  }
}

使用已关闭文档的 ID 调用 API,更新应该会失败,但这并没有发生。字段更新正常

显然我遗漏了一些东西。但是什么?

谢谢大家!

仅供有需要者参考。 我最终创建了以下特征:

<?php
 
namespace App\Traits;
use App\Exceptions\ImmutableModelException;

trait ImmutableModelTrait {
 
    public function __set($key, $value)
    {
        if ($this->isClosed)
        {
            throw new ImmutableModelException();
        }
        else {
            //do what Laravel normally does
            $this->setAttribute($key, $value);
        }
    }  
}

正如@mrhn 在一条评论中所述,我的第一个解决方案的问题是我在新模型实例上搜索“isImmutable”变量,但我没有将该变量保留在数据库 table.

所以现在我的“文档”table 有一个字段“isClosed”,当文档被认为已关闭时该字段变为真。