I'm using PDO, but I want to create my own class for more convenient work with the database.
My main idea in example with comments:
<?php
/**
* User entity. I want to save it into database.
* @Table(name="my_table")
*/
class User {
/**
* Special phpDoc values indicates that this variable should be stored into database.
* @Column(type="integer", autoincrement=true)
*/
private $id;
/**
* @Column(type="string", length=32)
*/
private $name;
/**
* @Column(type="string", length=64)
*/
private $password;
/**
* @Column(type="string", length=256)
*/
private $email;
public function __construct($id = NULL) {
if($id) {
// Load user data from DB
}
// If `id` not provided — we are creating new empty user, no need to load something
}
public function __set($var, $value) {
return (isset($this->$var)) ? $this->$var = $value : FALSE;
}
public function __get($var) {
return (isset($this->$var)) ? $this->$var : NULL;
}
}
// --------------------------------------------------
// Somewhere...
// --------------------------------------------------
$dataMgr = new DataManager(); // My class that will read object properties and store them in MySQL
// --------------------------------------------------
// Create new user
// --------------------------------------------------
$user = new User(); // Empty user
/*
* Set user data
*/
//$user->id = 1; // Autoincrement value
$user->name = 'TestUser';
$user->password = 'verystrongpassword';
$user->email = '[email protected]';
/*
* Read $user object properties and perform MySQL query if phpdoc block with special values found.
* INSERT query will be performed, because `id` field == NULL
*/
$dataMgr->save($user);
// --------------------------------------------------
// Update existing user
// --------------------------------------------------
$user = new User(50);
$user->password = 'newstrongpassword';
$dataMgr->save($user); // `id` in object != NULL, so perform UPDATE query
I know that there are good ORM frameworks, but they're very powerful and I don't need to use all their functions. Also I want to use my own mechanism in my own system.
What are the disadvantages? Perhaps I missed something, and my idea is not optimal, is it good practice? And what about Reflection performance?