Last active
January 26, 2026 16:57
-
-
Save D1360-64RC14/dfda18bbd59a6554ad3e946eac65982a to your computer and use it in GitHub Desktop.
DEMO. Using PHP Attributes and Reflection to extract model's tables names, ready to be queried.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| #[Attribute(Attribute::TARGET_PROPERTY)] | |
| class Column | |
| { | |
| public function __construct( | |
| public ?string $name = null | |
| ) {} | |
| } | |
| abstract class Model | |
| { | |
| public function __construct(array $attributes = []) | |
| { | |
| foreach ($attributes as $attr => $val) { | |
| if (property_exists($this, $attr)) { | |
| $this->{$attr} = $val; | |
| } | |
| } | |
| } | |
| public static function queryColumns(): array | |
| { | |
| $columns = []; | |
| $props = new ReflectionClass(static::class)->getProperties(); | |
| foreach ($props as $prop) { | |
| $columnAttrs = $prop->getAttributes(Column::class); | |
| if (count($columnAttrs) <= 0) continue; | |
| $columns[] = | |
| "'" . static::class . "'" . | |
| '.' . | |
| "'" . ($columnAttrs[0]->newInstance()->name ?? $prop->getName()) . "'"; | |
| } | |
| return $columns; | |
| } | |
| } | |
| class User extends Model | |
| { | |
| #[Column] | |
| public string $name; | |
| #[Column] | |
| public string $description; | |
| #[Column('user_type')] | |
| public ?string $userType; | |
| } | |
| $me = new User(['name' => 'Diego']); | |
| var_dump(User::queryColumns()); | |
| var_dump($me); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| array(3) { | |
| [0]=> | |
| string(13) "'User'.'name'" | |
| [1]=> | |
| string(20) "'User'.'description'" | |
| [2]=> | |
| string(18) "'User'.'user_type'" | |
| } | |
| object(User)#1 (1) { | |
| ["name"]=> | |
| string(5) "Diego" | |
| ["description"]=> | |
| uninitialized(string) | |
| ["userType"]=> | |
| uninitialized(?string) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment