PHP code example of theodorejb / phaster

1. Go to this page and download the library: Download theodorejb/phaster library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

theodorejb / phaster example snippets




use theodorejb\Phaster\{Entities, Prop, QueryOptions};

class Users extends Entities
{
    protected function getMap(): array
    {
        // map properties to columns in Users table
        return [
            'username' => 'uname',
            'firstName' => 'fname',
            'lastName' => 'lname',
            'isDisabled' => 'disabled',
            'role' => [
                'id' => 'role_id',
            ],
        ];
    }

    protected function getSelectProps(): array
    {
        // map additional properties for selecting/filtering and set output options
        return [
            new Prop('id', col: 'u.user_id'),
            new Prop('isDisabled', col: 'u.disabled', type: 'bool'),
            new Prop('role.id', col: 'u.role_id'),
            new Prop('role.name', col: 'r.role_name'),
        ];
    }

    protected function getBaseQuery(QueryOptions $options): string
    {
        return "SELECT {$options->getColumns()}
                FROM Users u
                INNER JOIN Roles r ON r.role_id = u.role_id";
    }

    protected function getDefaultSort(): array
    {
        return ['username' => 'asc'];
    }
}

use PeachySQL\QueryBuilder\SqlParams;
// ...
protected function getBaseSelect(QueryOptions $options): SqlParams
{
    $sql = "WITH num_orders AS
            (
                SELECT user_id, COUNT(*) as orders
                FROM Orders
                WHERE category_id = ?
                GROUP BY user_id
            )
            SELECT {$options->getColumns()}
            FROM Users u
            INNER JOIN num_orders n ON n.user_id = u.user_id";

    return new SqlParams($sql, [321]);
}
// ...



use My\DatabaseFactory;
use theodorejb\Phaster\{Entities, EntitiesFactory};

class MyEntitiesFactory implements EntitiesFactory
{
    public function createEntities($class): Entities
    {
        return new $class(DatabaseFactory::getDb());
    }
}



use theodorejb\Phaster\RouteHandler;

$phaster = new RouteHandler(new MyEntitiesFactory());

$app->get('/users', $phaster->search(Users::class));
$app->get('/users/{id}', $phaster->getById(Users::class));
$app->post('/users', $phaster->insert(Users::class));
$app->put('/users/{id}', $phaster->update(Users::class));
$app->patch('/users/{id}', $phaster->patch(Users::class));
$app->delete('/users/{id}', $phaster->delete(Users::class));