PHP Classes
elePHPant
Icontem

Simple Active Record: Store and fetch data with Active Records pattern

Recommend this page to a friend!

  Author Author  
Name: Lars Moelleken <contact>
Classes: 19 packages by
Country: Germany Germany
Innovation award
Innovation award
Nominee: 8x


  Detailed description   Download Download .zip .tar.gz  
This package can store and fetch data with Active Records pattern.

It comes with several classes that provides a fluent interface for creating objects that access databases and map the object values to database table records using the Active Record Design pattern.

Details

Build Status Coverage Status Codacy Badge Latest Stable Version Total Downloads License

:ring: Simple Active Record

This is a simple Active Record Pattern compatible with PHP 7+ that provides a simple and _secure_ interaction with your database using :gem: "Simple MySQLi" at its core. This is perfect for small scale applications such as cron jobs, facebook canvas campaigns or micro frameworks or sites.

Get "Simple Active Record"

You can download it from here, or require it using composer.

  {
      "require": {
        "voku/simple-active-record": "1.*"
      }
  }

Install via "composer require"

  composer require voku/simple-active-record

Starting the driver

  use voku\db\DB;

  require_once 'composer/autoload.php';

  $db = DB::getInstance('yourDbHost', 'yourDbUser', 'yourDbPassword', 'yourDbName');
  
  // example
  // $db = DB::getInstance('localhost', 'root', '', 'test');

Multiton && Singleton

You can use `DB::getInstance()` without any parameters and you will get your (as "singleton") first initialized connection. Or you can change the parameter and you will create an new "multiton"-instance which works like an singleton, but you need to use the same parameters again, otherwise (without the same parameter) you will get an new instance.

Doctrine/DBAL as parent driver

  use voku\db\DB;

  require_once 'composer/autoload.php';
  
  $connectionParams = [
      'dbname'   => 'yourDbName',
      'user'     => 'yourDbUser',
      'password' => 'yourDbPassword',
      'host'     => 'yourDbHost',
      'driver'   => 'mysqli', // 'pdo_mysql' || 'mysqli'
      'charset'  => 'utf8mb4',
  ];
  $config = new \Doctrine\DBAL\Configuration();
  $doctrineConnection = \Doctrine\DBAL\DriverManager::getConnection(
      $connectionParams,
      $config
  );
  $doctrineConnection->connect();

  $db = DB::getInstanceDoctrineHelper($doctrineConnection);

Using the "ActiveRecord"-Class (OOP database-access)

A simple implement of active record pattern via Arrayy.

setDb(DB $db)

set the DB connection.

  $db = DB::getInstance('YOUR_MYSQL_SERVER', 'YOUR_MYSQL_USER', 'YOUR_MYSQL_PW', 'YOUR_DATABASE');
  ActiveRecord::setDb($db);

insert() : boolean|int

This function can build insert SQL queries and can insert the current record into database. If insert was successful, it will return the new id, otherwise it will return false or true (if there are no dirty data).

  $user = new User();
  $user->name = 'demo';
  $user->password = password_hash('demo', PASSWORD_BCRYPT, ["cost" => 15]);
  $user_id = $user->insert();
  
  var_dump($user_id); // the new id 
  var_dump($user->id); // also the new id 
  var_dump($user->getPrimaryKey()); // also the new id 

fetch(integer $id = null) : boolean|\ActiveRecord

This function can fetch one record and assign in to current object. If you call this function with the $id parameter, it will fetch records by using the current primary-key-name.

  $user = new User();

  $user->notnull('id')->order('id desc')->fetch();
  
  // OR //
  
  $user->fetch(1);
  
  // OR //
  
  $user->fetchById(1); // thows "FetchingException" if the ID did not exists
  
  // OR //
  
  $user->fetchByIdIfExists(1); // return NULL if the ID did not exists
  
  var_dump($user->id); // (int) 1
  var_dump($user->getPrimaryKey()); // (int) 1

fetchAll() : $this[]

This function can fetch all records in the database and will return an array of ActiveRecord objects.

  $user = new User();

  $users = $user->fetchAll();
  
  // OR //
  
  $users = $user->fetchByIds([1]);
  
  // OR //
  
  $users = $user->fetchByIdsPrimaryKeyAsArrayIndex([1]);
    
  var_dump($users[0]->id) // (int) 1
  var_dump($users[0]->getPrimaryKey()); // (int) 1

update() : boolean|int

This function can build update SQL queries and can update the current record in database, just write the dirty data into database. If update was successful, it will return the affected rows as int, otherwise it will return false or true (if there are no dirty data).

  $user = new User();
  $user->notnull('id')->orderby('id desc')->fetch();
  $user->email = 'test@example.com';
  $user->update();

delete() : boolean

This function can delete the current record in the database.

Active Record | SQL part functions

select()

This function can set the select columns.

  $user = new User();
  $user->select('id', 'name')->fetch();

from()

This function can set the table to fetch record from.

  $user = new User();
  $user->select('id', 'name')->from('user')->fetch();

join()

This function can set the table to fetch record from.

  $user = new User();
  $user->join('contact', 'contact.user_id = user.id')->fetch();

where()

This function can set where conditions.

  $user = new User();
  $user->where('id=1 AND name="demo"')->fetch();

group()

This function can set the "group by" conditions.

  $user = new User();
  $user->select('count(1) as count')->group('name')->fetchAll();

order()

This function can set the "order by" conditions.

  $user = new User();
  $user->order('name DESC')->fetch();

limit()

This function can set the "limit" conditions.

  $user = new User();
  $user->order('name DESC')->limit(0, 1)->fetch();

Active Record | WHERE conditions

equal()/eq()

  $user = new User();
  $user->eq('id', 1)->fetch();

notEqual()/ne()

  $user = new User();
  $user->ne('id', 1)->fetch();

greaterThan()/gt()

  $user = new User();
  $user->gt('id', 1)->fetch();

lessThan()/lt()

  $user = new User();
  $user->lt('id', 1)->fetch();

greaterThanOrEqual()/ge()/gte()

  $user = new User();
  $user->ge('id', 1)->fetch();

lessThanOrEqual()/le()/lte()

  $user = new User();
  $user->le('id', 1)->fetch();

like()

  $user = new User();
  $user->like('name', 'de')->fetch();

in()

  $user = new User();
  $user->in('id', [1, 2])->fetch();

notIn()

  $user = new User();
  $user->notin('id', [1, 3])->fetch();

isNull()

  $user = new User();
  $user->isnull('id')->fetch();

isNotNull()/notNull()

  $user = new User();
  $user->isNotNull('id')->fetch();

Active Record | Demo

Include && Init

use voku\db\DB;
use voku\db\ActiveRecord;

require_once 'composer/autoload.php';

$db = DB::getInstance('YOUR_MYSQL_SERVER', 'YOUR_MYSQL_USER', 'YOUR_MYSQL_PW', 'YOUR_DATABASE');
ActiveRecord::setDb($db);

Define Class

namespace demo;

use voku\db\ActiveRecord;

/
 * @property int       $id
 * @property string    $name
 * @property string    $password
 * @property Contact[] $contacts
 * @property Contact   $contact
 */
class User extends ActiveRecord {
  public $table = 'user';
  public $primaryKey = 'id';
  
  public $relations = [
    // format is [$relation_type, $child_namespaced_classname, $foreign_key_of_child]
    'contacts' => [
      self::HAS_MANY, 
      'demo\Contact', 
      'user_id'
    ],
    'contacts_with_backref' => [
        self::HAS_MANY,
        'demo\Contact',
        'user_id',
        null,
        'user',
    ],
    // format may be [$relation_type, $child_namespaced_classname, $foreign_key_of_child, $array_of_sql_part_functions]
    'contact' => [
      self::HAS_ONE, 
      'demo\Contact', 
      'user_id', 
      [
        'where' => '1', 
        'order' => 'id desc',
      ],
    ],
  ];
}

/
 * @property int    $id
 * @property int    $user_id
 * @property string $email
 * @property string $address
 * @property User   $user
 */
class Contact extends ActiveRecord {
  public $table = 'contact';
  public $primaryKey = 'id';
  
  public $relations = [
    // format is [$relation_type, $parent_namespaced_classname, $foreign_key_in_current_table]
    'user' => [
      self::BELONGS_TO, 
      'demo\User', 
      'user_id'
    ],
  ];
}

Init data (for testing - use migrations for this step, please)

CREATE TABLE IF NOT EXISTS user (
  id INTEGER PRIMARY KEY, 
  name TEXT, 
  password TEXT 
);

CREATE TABLE IF NOT EXISTS contact (
  id INTEGER PRIMARY KEY, 
  user_id INTEGER, 
  email TEXT,
  address TEXT
);

Insert one User into database.

use demo\User;

$user = new User();
$user->name = 'demo';
$user->password = password_hash('demo', PASSWORD_BCRYPT, ["cost" => 15]);
$user_id = $user->insert();

var_dump($user_id); // the new id 
var_dump($user->id); // also the new id 
var_dump($user->getPrimaryKey()); // also the new id 

Insert one Contact belongs the current user.

use demo\Contact;

$contact = new Contact();
$contact->address = 'test';
$contact->email = 'test1234456@domain.com';
$contact->user_id = $user->id;

var_dump($contact->insert()); // the new id 
var_dump($contact->id); // also the new id 
var_dump($contact->getPrimaryKey()); // also the new id 

Example to using relations

use demo\User;
use demo\Contact;

$user = new User();

// fetch one user
var_dump($user->notnull('id')->orderby('id desc')->fetch());

echo "\nContact of User # {$user->id}\n";
// get contacts by using relation:
//   'contacts' => [self::HAS_MANY, 'demo\Contact', 'user_id'],
var_dump($user->contacts);

$contact = new Contact();

// fetch one contact
var_dump($contact->fetch());

// get user by using relation:
//    'user' => [self::BELONGS_TO, 'demo\User', 'user_id'],
var_dump($contact->user);

Changelog

See CHANGELOG.md.


  Classes of Lars Moelleken  >  Simple Active Record  >  Download Download .zip .tar.gz  >  Support forum Support forum  >  Blog Blog  >  RSS 1.0 feed RSS 2.0 feed Latest changes  
Name: Simple Active Record
Base name: simple-active-record
Description: Store and fetch data with Active Records pattern
Version: 1.0.0
PHP version: 7
License: MIT/X Consortium License
 
  Groups   Dependencies   Applications   Files Files  

  Groups  
Group folder image PHP 5 Classes using PHP 5 specific features View top rated classes
Group folder image Databases Database management, accessing and searching View top rated classes
Group folder image Design Patterns Implementations of well known design patterns View top rated classes


  Packages needed by this class  
Class DownloadWhy it is needed Dependency
Arrayy Download .zip .tar.gz to store the data into an Arrayy object Required
Simple MySQLi Class Download .zip .tar.gz as database connection layer Required

  Applications that use this package  
No pages of applications that use this class were specified.

Add link image If you know an application of this package, send a message to the author to add a link here.

  Files folder image Files  
File Role Description
Files folder imagesrc (1 directory)
Files folder imagetests (5 files)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file .scrutinizer.yml Data Auxiliary data
Accessible without login Plain text file .styleci.yml Data Auxiliary data
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file CHANGELOG.md Data Auxiliary data
Accessible without login Plain text file circle.yml Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpcs.php_cs Example Example script
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  src  
File Role Description
Files folder imagevoku (1 directory)

  Files folder image Files  /  src  /  voku  
File Role Description
Files folder imagedb (3 files, 1 directory)

  Files folder image Files  /  src  /  voku  /  db  
File Role Description
Files folder imageexceptions (1 file)
  Plain text file ActiveRecord.php Class Class source
  Plain text file ActiveRecordExpressions.php Class Class source
  Plain text file ActiveRecordExpressionsWrap.php Class Class source

  Files folder image Files  /  src  /  voku  /  db  /  exceptions  
File Role Description
  Plain text file ActiveRecordException.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Plain text file ActiveRecordTest.php Class Class source
  Accessible without login Plain text file bootstrap.php Aux. Auxiliary script
  Plain text file FoobarContact.php Class Class source
  Plain text file FoobarUser.php Class Class source
  Plain text file FoobarUserContactJoin.php Class Class source

Download Download all files: simple-active-record.tar.gz simple-active-record.zip
NOTICE: if you are using a download manager program like 'GetRight', please Login before trying to download this archive.