Skip to main content

Transform PHP 8 class to a Database table like a framework

Transform PHP 8 class to a Database table like a framework

Transform PHP 8 class to a database table

Use #reflection #api in #php8 to transform PHP 8 class to a database table. In this blog post you will learn how to map a class properties into #MySQL table and columns.

 

Why do you need to transform PHP 8 class to a database table?

The logic is important to understand the #drupal11 #entityapi and making of custom entities. Also, you need to understand how reflection API works behind the scene so that you can adopt new way of hooks implementation in Drupal 11.

Problem

We will take an example of User class that has 3 properties userName, password and salary. I need a database table with name exactly the same as my class name and columns exactly the same as my user class has properties.

Solution

As a developer you may have faced this scenario in your day to day development. So let's create a class and add some properties. Later we will use PHP Reflection Class to read the property names and values to create a database table.


A PHP 8 class

<?php

namespace Bhimmu\Php84\Entities;

class User {

    public function __construct(
        private string $userName,
        private string $password,
        private string $salary) {}
}

Parse the PHP 8 class using Reflection Class

<?php

use Bhimmu\Php84\Entities\User;


$user = new User(
    userName: "VARCHAR(35) PRIMARY KEY",
    password: "VARCHAR(255)",
    salary: "INT"
);

$reflection = new ReflectionClass($user);

$properties = $reflection->getProperties();

$raw_query = 'CREATE TABLE ' . $reflection->getShortName() . '(';

foreach ($properties as $key => $property) {
    if ($key < count($properties) - 1) {
        $raw_query .= $property->getName() . ' ' . $property->getValue($user) . ', ';
    } else {
        $raw_query .= $property->getName() . ' ' . $property->getValue($user) . ')';
    }
}

echo $raw_query;

Output of the above example

CREATE TABLE User(userName VARCHAR(35) PRIMARY KEY, password VARCHAR(255), salary INT)

Above output can be dynamically passed to a Database class that will execute this SQL command to create a desired table.

Conclusion

Like a framework where you are writing entities and framework map the entity to a database table with same name and columns same as class properties. You can use #ReflectionAPI in #php8.

If you want to learn the trick through video then visit my YouTube Vlog.