Creating multiple PHP objects from one PDO array (no template)

If you want to get one object from the database, PDO is very useful:

$obj = $handle->fetchAll(PDO::FETCH_CLASS, $obj_name);

If you expect multiple class types to return on the same line (for example: when executing a JOIN), PDO is less useful:

$handle->fetchAll(PDO::FETCH_ASSOC);

... followed by some data matching in the resulting array . Good - except for every method I came up with to achieve this, it looks awful.

My question is : how can I create an instance of several objects from the same array in a graceful, reliable way, when the contents of this array can reflect everything, not a single one, no more than the ones that the classes require?

Example:

, PDO $vars = ('a' => 1, 'b' => 2, 'c' => 3, 'x' => 7, 'y' => 8, 'z' => 9), ABC ( $a, $b $c) XYZ ($x, $y, $z) .

1

class ABC {
    private $a, $b, $c;
    function __construct ($a = null, $b = null, $c = null) {
        $this->$a = $a ? $a : $this->a;
        $this->$b = $b ? $b : $this->b;
        ...

( / /, - )

2

function ABCFactory($vars = array()) {
    return new ABC($vars['a'], $vars['b']....

(, , $vars. , isset(), )

3

foreach ($vars AS $key => $value) {
    eval("if (isset(\$key) && \$value) \$this->$key = '$value';");
}

( , , , , , ... eval(), !:])

dockeryZ , mleko . , , . :

$def_vars = get_object_vars($this);
foreach ($vars AS $key => $value) {
    if (array_key_exists($key, $def_vars)) $this->{$key}=$value;
}

, , Johan Perez ... GET POST!

+4
2

<?php
class Name {
    public function __construct($data) {
        foreach($data as $key=>$val){
            $this->{$key}=$val;
        }

    }
}
+1

. , , Getters Setters. :

class Person {
    private $birthDate;
    private $parents;

    public function getBirthDate(){
        return $this->birthDate;
    }

    public function setBirthDate($birthDate){
        $this->birthDate = $birthDate;
    }

    public function getParents(){
        return $this->parents;
    }

    public function setParents($parents){
        $this->parents = $parents;
    }
}

, , : . -, . ( , ...). .

, , , , . , , - , . , , , , .

- , , . :

class Person {
    private $birthDate;
    private $parents;

    public function getBirthDate(){
        if (isset($this->birthDate) {
            return $this->birthDate;
        else {
            return new DateTime('NOW');
        }
    }

    public function setBirthDate($birthDate){
        if ($birthDate instanceof DateTime){
            $this->birthDate = $birthDate;
        } else {
            throw new InvalidArgumentException("Person::birthDate should be an instance of DateTime");
        }
    }

    public function getParents(){
        if (isset($this->parents) {
            return $this->parents;
        else {
            return new array("father" => null, "mother" => null);
        }
    }

    public function setParents($parents){
        if (is_array($parents) && array_keys($parents) == array("father", "mother")){
           if ($parents["father"] instanceof Person && $parents["mother"] instanceof Person){
               $this->parents = $parents;
           } else {
               throw new InvalidArgumentException("Father and Mother should be instances of Person class.");
           }
        } else {
            throw new Invalid ArgumentException("Person::parents should be an array and in must contain only ['father'] and ['mother'] keys.");
        }
    }

   public static function createPersonFromPDO($pdoArray){
       // Check here if $pdoArray is an array and it is a valid array.

       $person = new Person();

       foreach($pdoArray as $key => $value){
            switch($key){
                case "birthDate":
                    $person->setBirthDate($value);
                break;
                case "parents":
                    $person->setParents($value);
                break;
            }
       }

       return $person;
   } 
}
+1

Source: https://habr.com/ru/post/1537391/


All Articles