Greg ORM
, (*1)
A lightweight but powerful ORM(Object-Relational Mapping) library for PHP., (*2)
Gest Started with establishing a Database Connection,
create an Active Record Model of a database table
and write your first queries using the Query Builder., (*3)
Why use Greg ORM?
You can read about it in the next article: pending, (*4)
Get Started
Requirements
Installation
You can add this library as a local, per-project dependency to your project using Composer:, (*5)
composer require greg-md/php-orm
, (*6)
Supported Drivers
In progress:, (*7)
Database Connection - Quick Start
There are two ways of creating a database connection:, (*8)
- Instantiate a database connection for a specific driver;
- Instantiate a connection manager to store multiple database connections.
The connection manager implements the same connection strategy.
This means that you can define a connection to act like it., (*9)
In the next example we will use a connection manager to store multiple connections of different drivers., (*10)
// Instantiate a Connection Manager
$manager = new \Greg\Orm\Connection\ConnectionManager();
// Register a MySQL connection
$manager->register('mysql_connection', function() {
return new \Greg\Orm\Connection\MysqlConnection(
new \Greg\Orm\Connection\Pdo('mysql:dbname=example_db;host=127.0.0.1', 'john', 'doe')
);
});
// Register a SQLite connection
$manager->register('sqlite_connection', function() {
return new \Greg\Orm\Connection\SqliteConnection(
new \Greg\Orm\Connection\Pdo('sqlite:/var/db/example_db.sqlite')
);
});
// Make the manager to act as "mysql_connection"
$manager->actAs('mysql_connection');
Now you can work with this manager:, (*11)
// Fetch a statement from "sqlite_connection"
$manager->connection('sqlite_connection')
->select()
->from('Table')
->fetchAll();
// Fetch a statement from mysql_connection, which is used by default
$manager
->select()
->from('Table')
->fetchAll();
Full documentation can be found here., (*12)
Active Record Model - Quick Start
The Active Record Model represents a table schema, an entity or a collection of entities of that table,
integrated with the Query Builder to speed up your coding process., (*13)
Let's say you have Users
table:, (*14)
CREATE TABLE `Users` (
`Id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`Email` VARCHAR(255) NOT NULL,
`Password` VARCHAR(32) NOT NULL,
`SSN` VARCHAR(32) NULL,
`FirstName` VARCHAR(50) NULL,
`LastName` VARCHAR(50) NULL,
`Active` TINYINT(1) UNSIGNED NOT NULL DEFAULT '1',
PRIMARY KEY (`Id`),
UNIQUE (`Email`),
UNIQUE (`SSN`),
KEY (`Password`),
KEY (`FirstName`),
KEY (`LastName`),
KEY (`Active`)
);
Let's create the model for that table and configure it:, (*15)
class UsersModel extends \Greg\Orm\Model
{
// Define table alias. (optional)
protected $alias = 'u';
// Cast columns. (optional)
protected $casts = [
'Active' => 'boolean',
];
// Table name (required)
public function name(): string
{
return 'Users';
}
// Create abstract attribute "FullName". (optional)
public function getFullNameAttribute(): string
{
return implode(' ', array_filter([$this['FirstName'], $this['LastName']]));
}
// Change "SSN" attribute. (optional)
public function getSSNAttribute(): string
{
// Display only last 3 digits of the SSN.
return str_repeat('*', 6) . substr($this['SSN'], -3, 3);
}
// Extend SQL Builder. (optional)
public function whereIsNoFullName()
{
$this->whereIsNull('FirstName')->whereIsNull('LastName');
return $this;
}
}
Now, let's instantiate that model. The only thing you need is a Database Connection:, (*16)
// Initialize the model.
$usersModel = new UsersModel($connection);
Working with table schema
// Display table name.
print_r($usersModel->name()); // result: Users
// Display auto-increment column.
print_r($usersModel->autoIncrement()); // result: Id
// Display primary keys.
print_r($usersModel->primary()); // result: ['Id']
// Display all unique keys.
print_r($usersModel->unique()); // result: [['Email'], ['SSN']]
Working with a single row
// Create a user.
$user = $usersModel->create([
'Email' => 'john@doe.com',
'Password' => password_hash('secret'),
'SSN' => '123456789',
'FirstName' => 'John',
'LastName' => 'Doe',
]);
// Display user email.
print_r($user['Email']); // result: john@doe.com
// Display user full name.
print_r($user['FullName']); // result: John Doe
print_r($user['SSN']); // result: ******789
// Display if user is active.
print_r($user['Active']); // result: true
// Display user's primary keys.
print_r($user->getPrimary()); // result: ['Id' => 1]
Working with a row set
// Create some users.
$usersModel->create([
'Email' => 'john@doe.com',
'Password' => password_hash('secret'),
'Active' => true,
]);
$usersModel->create([
'Email' => 'matt@damon.com',
'Password' => password_hash('secret'),
'Active' => false,
]);
$usersModel->create([
'Email' => 'josh@barro.com',
'Password' => password_hash('secret'),
'Active' => false,
]);
// Fetch all inactive users from database.
$inactiveUsers = $usersModel->whereIsNot('Active')->fetchAll();
// Display users count.
print_r($inactiveUsers->count()); // result: 2
// Display users emails.
print_r($inactiveUsers->get('Email')); // result: ['matt@damon.com', 'josh@barro.com']
// Activate all users in the row set.
$inactiveUsers->set('Active', true)->save();
print_r($inactiveUsers[0]['Active']); // result: true
print_r($inactiveUsers[1]['Active']); // result: true
Working with Query Builder
Select users that doesn't have first and last names., (*17)
$users = $usersModel
->whereIsNoFullName()
->orderAsc('Id')
->fetchAll();
Update an user:, (*18)
$usersModel
->where('Id', 10)
->update(['Email' => 'foo@bar.com']);
Full documentation can be found here., (*19)
Query Builder - Quick Start
The Query Builder provides an elegant way of creating SQL statements and clauses on different levels of complexity., (*20)
You can easily instantiate a Query Builder with a Database Connection., (*21)
Let's say you have Students
table., (*22)
Find students names that lives in Chisinau and were born in 1990:, (*23)
$students = $connection->select()
->columns('Id', 'Name')
->from('Students')
->where('City', 'Chisinau')
->whereYear('Birthday', 1990)
->fetchAll();
Update the grade of a student:, (*24)
$connection->update()
->table('Students')
->set('Grade', 1400)
->where('Id', 10)
->execute();
Delete students that were not admitted in the current year:, (*25)
$connection->delete()
->from('Students')
->whereIsNot('Admitted')
->execute();
Add a new student:, (*26)
$query = $connection->insert()
->into('Students')
->data(['Name' => 'John Doe', 'Year' => 2017])
->execute();
Full documentation can be found here., (*27)
Documentation
License
MIT © Grigorii Duca, (*28)
Huuuge Quote
, (*29)