GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - flightphp/active-record: Micro Active Record library in PHP, supports chain calls, events, and relations.

BranchesTags
Open more actions menu

Latest commit

 

History

199 Commits
199 Commits

Folders and files

NameName
Last commit message
Last commit date
src
src
 
 
tests
tests
 
 
.gitignore
.gitignore
 
 
AGENTS.md
AGENTS.md
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
composer.json
composer.json
 
 
phpcs.xml
phpcs.xml
 
 
phpunit.xml
phpunit.xml
 
 

Repository files navigation

FlightPHP Active Record

Latest Stable Version License PHP Version Require Dependencies

An active record is mapping a database entity to a PHP object. Spoken plainly, if you have a users table in your database, you can "translate" a row in that table to a User class and a $user object in your codebase. See basic example.

Installation

Simply install with Composer

composer require flightphp/active-record 

Basic Example

Let's assume you have the following table:

CREATE TABLE users (
  id INTEGER PRIMARY KEY, 
  name TEXT, 
  password TEXT 
);

Now you can setup a new class to represent this table:

/**
 * An ActiveRecord class is usually singular
 * 
 * It's highly recommended to add the properties of the table as comments here
 *
 * @property int    $id
 * @property string $name
 * @property string $password
 */ 
class User extends flight\ActiveRecord {
  public function __construct($databaseConnection)
  {
    parent::__construct($databaseConnection, 'users', [/* custom values */]);
  }
}

Now watch the magic happen!

// for sqlite
$database_connection = new PDO('sqlite:test.db'); // this is just for example, you'd probably use a real database connection

// for mysql
$database_connection = new PDO('mysql:host=localhost;dbname=test_db&charset=utf8bm4', 'username', 'password');

// or mysqli
$database_connection = new mysqli('localhost', 'username', 'password', 'test_db');
// or mysqli with non-object based creation
$database_connection = mysqli_connect('localhost', 'username', 'password', 'test_db');

$user = new User($database_connection);
$user->name = 'Bobby Tables';
$user->password = password_hash('some cool password');
$user->insert();
// or $user->save();

echo $user->id; // 1

$user->name = 'Joseph Mamma';
$user->password = password_hash('some cool password again!!!');
$user->insert();

echo $user->id; // 2

And it was just that easy to add a new user! Now that there is a user row in the database, how do you pull it out?

$user->find(1); // find id = 1 in the database and return it.
echo $user->name; // 'Bobby Tables'

And what if you want to find all the users?

$users = $user->findAll();

What about with a certain condition?

$users = $user->like('name', '%mamma%')->findAll();

See how much fun this is? Let's install it and get started!

Aggregate Queries

// Count rows with conditions
$user->count();
$user->eq('status', 'active')->count();

// Check if any rows match
$user->eq('name', 'Bobby')->exists(); // true

Scalar Extraction

// Get flat array of values from a single column
$user->pluck('name'); // ['Bobby', 'Joseph', ...]

// Get primary keys
$user->ids(); // [1, 2, ...]

Convenient Finders

// Get first/last record (ordered by primary key)
$user->first();
$user->last();

// Update a single attribute on a loaded record
$loadedUser = $user->find(1);
$loadedUser->updateAttribute('name', 'New Name');

Distinct

$user->distinct()->pluck('status'); // ['active', 'inactive', ...]

Batch Operations

// Update multiple rows
$user->eq('status', 'inactive')->updateAll(['status' => 'active']);

// Delete multiple rows (use with caution!)
$user->eq('status', 'deleted')->deleteAll();

Timestamps

Automatically set created_at and updated_at columns:

class User extends ActiveRecord
{
    protected bool $timestamps = true;

    public function __construct($databaseConnection)
    {
        parent::__construct($databaseConnection, 'users');
    }
}

Scopes

Define reusable query chains as methods:

class User extends ActiveRecord
{
    public function active(): self
    {
        return $this->eq('status', 'active');
    }

    public function recent(int $days = 7): self
    {
        return $this->ge('created_at', date('Y-m-d', strtotime("-{$days} days")));
    }
}

// Usage
$users = (new User($db))->active()->findAll();
$recent = (new User($db))->active()->recent(30)->findAll();

Transactions

Wrap multiple operations in a transaction:

$user->transaction(function ($model) {
    $model->insert();
    // Automatically commits on success, rolls back on exception
});

Documentation

Head over to the documentation page to learn more about usage and how cool this thing is! :)

License

MIT

About

Micro Active Record library in PHP, supports chain calls, events, and relations.

docs.flightphp.com/awesome-plugins/active-record

Topics

active-recorddatabaseflightphpflipping-sweetmappermysqlormquery-buildersqlite

Resources

Readme
MIT license
Activity
Custom properties

Stars

20 stars

Watchers

1 watching

Forks

7 forks
Report repository

Releases

Packages

Used by

Contributors

Languages

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.