2017-09-23 1 views
0

다른 프레임 워크 또는 pure-PHP로 작업 할 때 모델 속성을 보호합니다. 그런 다음 공개 게터와 설정자를 필요에 따라 만들고 프록시에 __get()__set()을 사용하여 프록시를 만듭니다. 이것은 내가 밤에 잠을 자도록 도와줍니다.Laravel 모델 속성을 보호하는 방법

최근에 나는 Laravel을 사용하기 시작했고 나는 Eloquent 모델이 '보호되지 않은'방법에 놀랐습니다. $guarded$fillable 속성을 사용하여 대량 할당을 제어 할 수 있지만 우발적 인 액세스를위한 많은 여지가 남아 있음을 이해합니다.

예를 들어, 내 모델의 속성은 status입니다. 모델 생성시 기본값이 설정되며 $model->activate() 또는 $model->deactivate()이 호출 될 때만 수정해야합니다. 그러나 Laravel은 기본적으로 개발자가 직접 수정할 수 있습니다. 지금까지 볼 수있는 한,이를 막기위한 유일한 방법은 setter를 생성하고 호출 된 경우 예외를 throw하는 것입니다.

내가 누락 된 항목이 있습니까? 아마 나는 단지 긴장을 풀 필요가 있을까요? 기본적으로 안전한 Eloquent 모델을 구축하는 가장 좋은 방법은 무엇입니까?

답변

1

__get 및 __set 메서드를 재정의 할 수 있습니다. 모델 필드를 제어 할 수 있도록 protectedProperties 배열과 boolean 변수 protectedChecks를 정의해야합니다.

protected $protectedChecks = true; 

protected $protectedProperties = [ 'status' ]; 

protected $fillable = ['status']; 

public function __get($key) 
{ 
    return (in_array($key, $this->fillable) && !in_array($key, $this->protectedProperties)) ? $this->attributes[$key] : null; 
} 

public function __set($key, $value) 
{ 
    if(!$this->protectedChecks || !in_array($key, $this->protectedProperties)) 
      return parent::__set($key, $value); 
     trigger_error('Protected Field'); 
} 

public function activate() 
{ 
    $this->protectedChecks = false; 
    $this->status = 1; 
    $this->save(); // this is optional if you want to save the model immediately 
    $this->protectedChecks = true; 
} 

모든 모델을 사용하려면 위 모델을 BaseModel에 작성해야합니다.

0

당신은 시도 할 수 있습니다 :

<?php 

class User extends Eloquent { 

    protected $hidden = array('password', 'token'); 

}