A PHP library that allows you to easily create and define your models using PDO
FETCH_INTO made easy$ composer require lodev09/php-models
The main ModelsDB class is a PDO wrapper used to make CRUD much easier. It is a forked code from the php-pdo-wrapper-class
// connect to your database. Store the $db instance globally -- you only need to connect to your db ONCE!
$db = new ModelsDB(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);Available CRUD methods
$db->insert($sql, $binds) or $db->insert($table, $values)$db->select($sql, $binds)$db->row($sql, $binds) (same with select but will return single row)$db->update($sql, $binds) or $db->update('table', $values)$db->delete($sql, $binds) or $db->delete('table', $filters)The default style is PDO::FETCH_OBJ
Example:
$users = $db->select("SELECT * FROM users WHERE active = 1 AND username = :username", array('username' => 'lodev09'));
var_dump($users);The ModelsModel class is a parent class that can be inherited to a Model class. Inheriting this class allows you to automatically map the result "row" into your model class (table). This class basically uses the PDO::FETC_INTO style and made it easier for you. Here are the steps to link your table into a class:
ModelsDB instance (see above)$db = new ModelsDB(DB_HOST, DB_NAME, DB_USER, DB_PASSWORD);
ModelsModel::setDb($db);User.php classnamespace Models;
class User extends Model {
public function getName() {
return $this->name;
}
}// somewhere in your init.php
ModelsUser::register('users');Now, you can directly get the User instance from a query. Example:
$user = ModelsUser::row("SELECT id, name FROM users WHERE id = 1 AND active = 1");
// you can call the getName() method now
if ($user) {
$name = $user->getName();
echo 'His name is '.$name;
}All bugs, feature requests, pull requests, feedback, etc., are welcome. Visit my site at www.lodev09.com or email me at [email protected]
© 2018 - Coded by Jovanni Lo / @lodev09
Released under the MIT License. See LICENSE file.