Populating DTOs automatically in PHP

Depending on the form complexity, fill each DTO attribute from $ _REQUEST may be a lot of work. Of course, good frameworks solve this case easily. But if for some reason our framework don't implement this mapping, or if we aren't using any framework, and for each DTO attribute we must do something like $ dto-> seAttributeName ($ _REQUEST ['attributeName']), an alternative is to implement a simple function that does it for us.

The ​​function idea is to receive fields from form and fill an object with values present ​in these fields. The mapping is done in the form "objectName.attribute".

DTO Class:

 
  class UserDto {
    private $name;
    private $city_name;
    private $email;
    private $address;
   
    public function setName($name) {
        $this->name = $name;
    }
    public function getName() {
        return $this->name;
    }

    ...
     / * remaining get and set methods * /

  }

 

Page code:

 
    Name:
     
   
    Email: 
     
 
    City: 
         
       
    Address:
    

 

Php code:

 
    // DTO to populate.
    require_once('UserDto.php');

    // Class with method that populate DTO attributes.
    require_once('EntityUtil.php');
   
    // Initialize a new DTO.
    $userDto = new UserDto();

    // Populate DTO attributes in accordance with the values ​​sent.
    EntityUtil::autoSetFields($userDto, "user");

 

The first parameter of autoSetFields is the object to be filled. The second parameter must match the value of "name" attribute before "." on form; in this case, "user". The value after "." must correspond to the class attribute that we want to fill. Each attribute shall contain a corresponding set method. If the second parameter of the method autoSetFields is omitted, the class name must be infomed on form, starting with a lowercase letter. In this case instead of "user" it would be "userDto."

 

And finally the class that does the job:

 
class EntityUtil {
    static function autoSetFields($obj, $prefixName = null) {
            $keys = array_keys($_REQUEST);

            if($prefixName == null) {
                    $prefixName = get_class($obj);
                    $prefixName[0] = strtolower($prefixName[0]);
            } 
            $prefixName .= "_";

            foreach($keys as $key) {
                    if(strstr($key, $prefixName)) {
                            $fName = explode($prefixName, $key);
                            $fName[1][0] = strtoupper($fName[1][0]);
                            $obj->{"set".$fName[1]}($_REQUEST[$key]);
                    }
            }
    }
}

 

The interesting point in this method is on line 15. It shows how simple and yet powerful PHP can be. Using curly braces we can execute PHP code from using strings. Our example concatenate the string "set" with the name of the attribute that so far do not even known. The result of this concatenation is the method to be invoked on the object. This approach allows a simpler way than the use of reflection (another possible solution here).

Comments

Excellent post! Really loved it, havent seen an artice this good in a while.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.