lundi 19 décembre 2022

PHP cast object in simple ORM

I would like to make a simple ORM in PHP for standard CRUD interaction with my db, I also want make it work in php5 for legacy compatibility.

I've written some classes to do this and it works, but not completely as I would.

This is the idea. I have an abstrac class called ModelBase which has a property (tableName) and some metods like select, insert, update and delete, plus has an abstract method, getData, that will be implemented by the classes that will be implement ModelBase and should return object of correct type.

So, for example, I could have a class Users which implements ModelBase and one another class UserData which is the model with the property.

Here is the code:

abstract class ModelBase{
   private $tableName;

   public function __construct($tableName) { 
        $this->tableName = $tableName;
   }

   public function select{
       // make select query to db and retreive data
       // ...

       $resData = [];
       while($dataRow = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
           $resData[] = $this->getObjectData($dataRow); // implemented in child class
       }
       return $resData;
   }

   public function insert(){ /* ... */}
   public function update(){ /* ... */}
   public function delete(){ /* ... */}
   abstract function getObjectData($data); // maps the results
}

class UserData {
   public $id;
   public $name;
   public $surname;
   public $email;
   // other fields

   public function __construct() {}
}

class User implements ModelBase {
    private $tableName = 'users';

    public function __construct() { 
        parent::__construct($this->tableName);
    }

    public function getObjectData($dataRow) {
        $o = new UserData ();

        // mapping dataRow to object fields
        $o->id = $dataRow['ID'];
        // ....

        return $o;
   }
}

So I use my classes in this way:

$users = new Users();
$u = users->select();
$firstUser = $u[0]; // I get my user if exists

In $firstUser I'll get my object with property and correct data but I would like to have that also my IDE (vsCode in this case) would recognize the object type in order to suggest the correct properties. So if I write $firstUser-> I would like to see field suggestions (id, name, surname, ...) from UserData and for other xyzData classes as well.

What I should do to improve my classes in order to see property suggestions when I use my objects, also in php5?

Aucun commentaire:

Enregistrer un commentaire