문제

내가하려는 것은 일반적인 PHP 객체가있는 도메인 모델을 만드는 것입니다. 모든 인프라 작업을 수행 할 라이브러리를 만들고 있습니다. 그래서 내 모델 중 하나가 다음과 같습니다

class Project {
  public $id;
  public $name;
  public $typeId;

  private $type;

  public function getType() {
    return $this->type;
  }

  public function setType(Type $type) {
    $this->typeId = $type->id;
    $this->type = $type;
  }
}

이제 새 프로젝트를 만들고 전화하십시오 setType 유효한 유형 객체를 사용하면 프로젝트와 유형이 모두 저장된 ORM을 사용하여 프로젝트 인스턴스를 저장합니다. 그러나 프로젝트를로드하고 사용합니다 getType 방법 나는 ORM 이이 방법을 투명에서 객체를로드하도록 투명하게 수정하기를 원합니다. 그래서이 방법은 다음과 같습니다.

public function getType() {
  return $this->type;
}

투명하게 변경됩니다.

public function getType() {
  if (is_null($this->type) {
    $this->type = $this->adapter->findById('table', $this->typeId);
  }

  return $this->type; // or return parent::getType();
}

Outlet PHP는 Eval을 사용하여 Project_proxy라는 프로젝트에 대한 프록시 클래스를 생성하지만 때로는 프로젝트의 서브 클래스가 있으므로 방법이있는 경우 반사 API를 사용하여 솔루션을 검색하고 있습니다.

검색 Google이 있지만 어쨌든 메소드 동작을 변경할 수 없었습니다.

편집하다: 아니면 아울렛 PHP의 평가 방법을 사용하여 모델과 그 하위 클래스에 대한 프록시 클래스를 만드는 것이 좋습니다.

도움이 되었습니까?

해결책

There is no builtin way of doing this. And although you can do that using the PECL extension called runkit, I would strongly recommend finding another solution. Changing the implementation of functions you can't know anything about is very dangerous and might lead to bugs where debugging a single such bug can take longer than writing the if (is_null(... statements for all your functions.

BTW: don't use is_null(), since you might fetch null values from the database over and over again. You should store the fetched values in a separate variable.

다른 팁

Looking at the reflection doc on php.net, it appears to me it is impossible to modify on the flight a method.

You should try to do it in a different way.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top