2017-11-28 19 views
1

Doctrine 2 도메인에서 데이터를 가져 오는 "AutoMapper"와 유사한 기능/프레임 워크/패턴 찾기 엔티티/DTO를 만들고 해당 엔티티의 보호 된 속성을 View Model의 일치하는 공용 속성에 매핑합니다. UserUserViewModel 사이의 유일한 큰 차이는 UserViewModel 이름에 일치하는 공용 속성을 포함하는 반면, User은 (교리의 지침에 따라) 보호 백업 필드/설정 접근을 얻을 포함되어 있다는 것입니다PHP 5.x에서 공개 속성이있는 "View Model"에 대한 DTO/Domain Entity의 "AutoMapping"옵션

$userEntity = $this-em->find(User::class, 1);

$userViewModel = AutoMapper->Map($userEntity, new UserViewModel());

보호 된 지원 필드의 일부 [User]에 있습니다.

어떻게해야합니까? (바람직하게는 반영하지 않음)

도메인 엔티티에는 public get 접근자가 있으므로 솔루션에서 이러한 접근자를 활용할 수 있습니다.

답변

1

나를 위해이 문제를 해결하기 위해 PHP를위한 AutoMapper를 직접 구현했으나 효과적이었습니다. 이 메소드는 public 속성이나 public getter (규칙 기반 이름 지정)에서 대상 엔터티의 public 속성으로 매핑됩니다.

class Mapper 
{ 
    /** 
    * This method will attempt to source all public property values on $target from $source. 
    * 
    * By convention, it'll look for properties on source with the same name, 
    * .. and will fallback camel-cased get/set accessors to use. 
    * 
    * Note that underscores in properties will be translated to capital letters in camel-cased getters. 
    * 
    * @param $source object 
    * @param $target object 
    * @return object 
    * @throws Exception 
    */ 
    public static function Map($source, $target) 
    { 
     $targetProperties = get_object_vars($target); 
     $sourceProperties = get_object_vars($source); 

     foreach ($targetProperties as $name => $value) 
     { 
      // 
      // match properties 
      // 

      $matchingSourcePropertyExists = array_key_exists($name, $sourceProperties); 
      if ($matchingSourcePropertyExists) 
      { 
       $target->{$name} = $source->{$name}; 
       continue; 
      } 

      // 
      // fall back on matching by convention-based get accessors 
      // 

      $sourceMethods = get_class_methods(get_class($source)); 
      $getterName = "get" . self::convertToPascalCase($name); 
      $matchingGetAccessorExists = in_array($getterName, $sourceMethods); 
      if ($matchingGetAccessorExists) 
      { 
       $target->{$name} = $source->{$getterName}(); 
       continue; 
      } 

      // 
      // if we ever fail to map an entity on the target, throw 
      // 

      $className = get_class($target); 
      throw new Exception("Could not auto-map property $name on $className."); 
     } 

     return $target; 
    } 

    /** 
    * Converts this_kind_of_string into ThisKindOfString. 
    * @param $value string 
    * @return string 
    */ 
    private static function convertToPascalCase($value) 
    { 
     $value[0] = strtoupper($value[0]); 

     $func = create_function('$c', 'return strtoupper($c[1]);'); 

     return preg_replace_callback('/_([a-z])/', $func, $value); 
    } 
} 
:

희망이 사람을 도와 준다