Wallogit.com
2017 © Pedro Peláez
Model class for PDO
A PHP class for easily create/update/load database entries. All you need to do is extend this class from your model and enjoy the benefits. It uses PDO connection but I only tested with MySql. I am going to explain the usage with a simple user class., (*1)
Please write your tests well., (*2)
Extend your composer.json file with the following:, (*3)
{
"require": {
"subztep/modell": "dev-master"
}
}
Our user table will contains name and email. Each plural table require an id int primary key field. Optional created_at and updated_at datetime columns for log your updates, recommended., (*4)
CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(30) NOT NULL, `email` varchar(255) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Connect to database, (*5)
Modell::$pdo = new PDO('mysql:host=HOST;dbname=DBNAME;charset=utf8', 'USER', 'PASS');
Connect to memcache is optional. If connected, Modell cache your table's column details and make it faster., (*6)
Modell::$memcache = new Memcache;
Modell::$memcache->connect('localhost', 11211);
Create table users with primary key id, and add Modell class to your project, (*7)
class User extends Modell {
}
Furthermore, you can run any sql query, connection in singleton., (*8)
$query = Modell::$pdo->prepare($sql);
Create user, (*9)
$user = new User(); $user->name = 'John Doe'; $user->save();
Load user by id, (*10)
$user = new User(1); echo $user->name;
Update user by id, (*11)
$user = new User(1); $user->name = 'John Roe'; $user->save();