Categories

PHP micro-ORM

Posted on: November 1, 2020 by Dimitar Ivanov

php-orm is a micro-library built with PHP7 and PDO that simplify daily work with MySQL database.

php-orm
Figure 1. php-orm micro library
Table of contents

Requirements

  • PHP >= 7.1
  • PDO extension

Installation

If composer is not installed on your system yet, you may go ahead and install it using this command line:

$ curl -sS https://getcomposer.org/installer | php

Next, add the following require entry to the composer.json file in the root of your project.

"require" : {
    "riverside/php-orm" : "*"
}

Finally, use composer to install php-orm and its dependencies:

$ php composer.phar install

Configuration

php-orm expects the following environment variables at local level:

<?php
$_ENV['PHP_ORM_DSN']  = 'mysql:host=localhost;dbname=mydb';
$_ENV['PHP_ORM_USER'] = 'myuser';
$_ENV['PHP_ORM_PSWD'] = 'mypswd';

Include autoload in your project:

<?php
require __DIR__ . '/vendor/autoload.php';

Models

<?php
use PhpOrm\DB;

class User extends DB
{
    protected $table = 'users';

    protected $attributes = ['id', 'name', 'email'];

    public static function factory()
    {
        return new self();
    }
}

Query builder

To add a row use the insert() method.

User::factory()
    ->insert(['name' => 'John']);

To read a row by it's id column use the find() method.

User::factory()->find(1); 

To get multiple records use the get() method.

User::factory()->get();

To get the first record use the first() method.

User::factory()->first();

To edit a row use the update() method.

User::factory()
    ->where('id', '=', 1)
    ->update(['name' => 'John Smith']);

To delete a row use the delete() method.

User::factory()
    ->where('id', '=', 1)
    ->delete(); 

Downloads

The project is hosted on GitHub.

License

php-orm is licensed under the MIT license.

See also
Share this post

If you like the php-orm please share this link with your friends and colleagues.


0 Comments

Comments are closed