2017 © Pedro Peláez
 

library database

The Fistlab PHP Database Components

image

fist/database

The Fistlab PHP Database Components

  • Monday, February 13, 2017
  • by marktopper
  • Repository
  • 2 Watchers
  • 5 Stars
  • 0 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

Fistlab Database

StyleCI Build Status Total Downloads Latest Stable Version Latest Unstable Version License, (*1)

The Fistlab Database component is a database toolkit, providing an expressive query builder. It currently supports MySQL and SQLite., (*2)

Languages: php., (*3)

Installation

Install using Composer., (*4)

composer require fist/database

Preparing

The constructor accepts an instance of RepositoryInterface from fist/repository., (*5)

Example, (*6)

$db = new \Fist\Database\Database(
    $repository = new Fist\Repository\ArrayRepository([
        'default' => [
            'connection' => 'default',
            'driver' => 'mysql',
        ],
        'connections' => [
            'default' => [
                'driver' => 'mysql',
                'hostname' => '127.0.0.1',
                'database' => 'database',
                'username' => 'root',
                'password' => '',
            ],
        ],
        'drivers' => [
            'mysql' => \Fist\Database\Connectors\MysqlConnection::class,
        ],
    ])
);

I have made more setup at this gist., (*7)

Usage

Running raw statements

Raw statements can be ran by using the statement-method., (*8)

$db->statement("SELECT * FROM `users` WHERE `username` = 'mark'");

It also takes an optional second argument with parameters to bind. Let's do the same query but by using bindings instead., (*9)

$db->statement("SELECT * FROM `users` WHERE `username` = ?", ['mark'])

Selecting all rows

Select all rows from a table using the query builder is quite easy., (*10)

$users = $db->table('users')->get();

foreach ($users as $user) {
    echo "Hello ".$user->username;
}

Select single row

Often you might want to get just a single database row object, like the current logged in user., (*11)

This can be done quite easy as well., (*12)

$user = $db->table('users')->first();

echo "Hello ".$user->username;

Note that in case of no results. null will be returned. To get an exception instead use the firstOrFail-method., (*13)

Select specific columns

Want to select only specific columns, like username, name and age., (*14)

$db->table('users')->select(['username', 'name', 'age'])->get();

You can also use aliases for the selected columns, like you want to get name as fullname., (*15)

$db->table('users')->select(['username', ['name' => 'fullname'], 'age'])->get();

Where clauses

You can use where clauses to the query builder to filter your results., (*16)

Basic where clauses

By default the operator is = for where clauses., (*17)

$db->table('users')->where('username', 'mark')->first();
$db->table('users')->where('username', '=', 'mark')->first();

The two methods above will do exactly the same, however you can use a set of other operators., (*18)

$db->table('users')->where('username', '!=', 'mark')->first();
$db->table('users')->where('age', '>', 18)->first();
$db->table('users')->where('age', '<', 18)->first();
$db->table('users')->where('age', '>=', 18)->first();
$db->table('users')->where('age', '<=', 18)->first();
$db->table('users')->where('age', 'LIKE', 'ma%')->first();

The default behaviour of the where clauses are all using and for combining., (*19)

However you might want to use or for some situations., (*20)

$db->table('users')
    ->where('username', 'mark')
    ->orWhere('username', 'topper')
    ->first();

You mind want to group the where clauses in sub clauses., (*21)

$db->table('users')
    ->where('username', 'mark')
    ->orWhere(function ($query) {
        $query->where('username', 'topper')
            ->orWhere('name', 'Mark Topper')
    })
    ->first();
Where null

Want to use the where clause to filter value from that are not null., (*22)

$db->table('users')->whereNull('age')->get();
Where not null

Want to use the where clause to filter value from that are null., (*23)

$db->table('users')->whereNotNull('age')->get();

Joining

You can join additional tables using our joining methods., (*24)

Inner join table
$db->table('users')
    ->join('devices', 'users.id', '=', 'devices.user_id')
    ->get();

By default the operator is = for join clauses.
So you can actually use join('devices', 'users.id', 'devices.user_id'), (*25)

Outer join table
$db->table('users')
    ->outerJoin('devices', 'users.id', '=', 'devices.user_id')
    ->get();
Left join table
$db->table('users')
    ->leftJoin('devices', 'users.id', '=', 'devices.user_id')
    ->get();
Right join table
$db->table('users')
    ->rightJoin('devices', 'users.id', '=', 'devices.user_id')
    ->get();
Cross join table
$db->table('users')
    ->crossJoin('devices', 'users.id', '=', 'devices.user_id')
    ->get();
Advanced join clause
$db->table('users')
    ->join('devices', function ($join) {
        $join->on('users.id', '=', 'devices.user_id')
            ->where('devices.platform', 'ios');
    })
    ->get();

Order results

You can other by a column, while the second argument controls the direction of the sort and may be either asc or desc., (*26)

$db->table('users')
    ->orderBy('name', 'desc')
    ->get();

You can other by multiple columns., (*27)

$db->table('users')
    ->orderBy('fistname', 'desc')
    ->orderBy('lastname', 'desc')
    ->get();
Order by random

Randomize the order, (*28)

$db->table('users')
    ->orderByRandom()
    ->first();

Grouping results

You can group the results., (*29)

$db->table('users')
    ->groupBy('country')
    ->get();

Limit results (& offset)

Limiting results with an offset are often used, specially when paginating., (*30)

$db->table('users')
    ->limit(100)
    ->offset(100)
    ->get();

Count results

Count rows easily, (*31)

$users = $db->table('users')->count();

Raw expressions

Sometimes you may need to use a raw expression in a query., (*32)

$db->table('users')
    ->select([
        $db->raw('count(*) as user_count'),
        'status',
    ])
    ->groupBy('status')
    ->get();

Conditional clauses

Sometimes you might want to only run a certain part of your query when something is true. You may for instance implement and where statement that only applies if a user is logged in., (*33)

$currentUserId = 1;
$loggedIn = true;

$db->table('users')
    ->when($loggedIn, function ($query) {
        $query->where('id', '=', $currentUserId);
    })
    ->get();

Insert rows

The insert method accepts an array of column names and values., (*34)

$db->table('users')->insert([
    ['email' => 'mark@example.com', 'username' => 'mark'],
    ['email' => 'john@example.com', 'username' => 'john'],
]);

Or you can insert a single row., (*35)

$db->table('users')->insert(
    ['email' => 'mark@example.com', 'username' => 'mark']
);
Auto incrementing IDs

Want to insert a row and get the auto incremented ID? You can do this using the insertGetId method., (*36)

$id = $db->table('users')->insertGetId(
    ['email' => 'mark@example.com', 'username' => 'mark']
);

Update rows

Update name for the for the user with the username set to mark?, (*37)

$db->table('user')->where('username', 'mark')->update(['name' => 'Foobar']);

Deleting rows

Deleting rows have never been easier., (*38)

$db->table('users')->where('last_login', '<', '2016-01-01 00:00:00')->delete();

If you wish to truncate the entire table, which will remove all rows and reset the auto-incrementing ID to zero, you may use the truncate method., (*39)

$db->table('users')->truncate();

Connection swapping

Have multiple connections configured you may swap between connections. The default connection is used unless anything else specified., (*40)

$db->connection('connection-name')
    ->table('users')
    ->get();

The Versions

13/02 2017

dev-master

9999999-dev https://github.com/fistphp/database

The Fistlab PHP Database Components

  Sources   Download

MIT

The Requires

 

The Development Requires

by Mark Topper

database component fistlab fistphp