PHP code example of atk4 / data

1. Go to this page and download the library: Download atk4/data 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/ */

    

atk4 / data example snippets


$vipClientModel = (new Client($db))->addCondition('is_vip', true);

// express total for all VIP client invoices. The value of the variable is an object
$totalDueModel = $vipClientModel->ref('Invoice')->action('fx', ['sum', 'total']);

// single database query is executed here, but not before!
echo $totalDueModel->getOne();

Crud::addTo($app)->setModel(new Client($db), ['name', 'surname'], ['edit', 'archive']);

$api->rest('/clients', new Client($db));

$presentation->setModel($businessModel);

$grid = new \Atk4\Ui\Table();
$data = new Order($db);
$data->addCondition('is_new', true);
$data->addCondition('client_id', $_GET['client_id']);
$grid->setModel($data);

$html = $grid->render();

class JobReport extends Job
{
    protected function init(): void
    {
        parent::init();

        // Invoice contains Lines that may relevant to this job
        $invoice = new Invoice($this->getPersistence());

        // we need to ignore draft invoices
        $invoice->addCondition('status', '!=', 'draft');

        // build relation between job and invoice line
        $this->hasMany('InvoiceLines', ['model' => static function () use ($invoice) {
            return $invoice->ref('Lines');
        }])
            ->addField('invoiced', [
                'aggregate' => 'sum',
                'field' => 'total',
                'type' => 'atk4_money'
            ]);

        // build relation between Job and Timesheets
        $this->hasMany('Timesheets', ['model' => static function (Persistence $persistence) {
            // next we need to see how much is reported through timesheets
            $timesheet = new Timesheet($persistence);

            // timesheet relates to client, import client.hourly_rate as expression
            $timesheet->getReference('client_id')->addField('hourly_rate');

            // calculate timesheet cost expression
            $timesheet->addExpression('cost', ['expr' => '[hours] * [hourly_rate]']);

            return $timesheet;
        }])
            ->addField('reported', [
                'aggregate' => 'sum',
                'field' => 'cost',
                'type' => 'atk4_money'
            ]);

        // finally lets calculate profit
        $this->addExpression('profit', ['expr' => '[invoiced] - [reported]']);

        // profit margin could be also useful
        $this->addExpression('profit_margin', ['expr' => 'coalesce([profit] / [invoiced], 0)']);
    }
}

$grid = new \Atk4\Ui\Grid();
$data = new JobReport($db);
$grid->setModel($data);

$html = $grid->render();

$chart = new \Atk4\Chart\BarChart();
$data = new JobReport($db);

// BarChart wants aggregated data
$data->addExpression('month', ['expr' => 'month([date])']);
$aggregate = new AggregateModel($data);
$aggregate->setGroupBy(['month'], [
    'profit_margin' => ['expr' => 'sum'],
]);

// associate presentation with data
$chart->setModel($aggregate, ['month', 'profit_margin']);
$html = $chart->html();

$m = new Client($db);
echo $m->addCondition('vip', true)
    ->ref('Order')->ref('Line')->action('fx', ['sum', 'total'])->getOne();

$m = new Client($db);
$m->loadBy('name', 'Pear Company');
$m->ref('Order')
    ->save(['ref' => 'TBL1', 'delivery' => new DateTime('+1 month')])
    ->ref('Lines')->import([
        ['Table', 'category' => 'furniture', 'qty' => 2, 'price' => 10.5],
        ['Chair', 'category' => 'furniture', 'qty' => 10, 'price' => 3.25],
    ]);

class Client extends \Atk4\Data\Model
{
    public $table = 'client';

    protected function init(): void
    {
        parent::init();

        $this->addField('name');
        $this->addField('address');

        $this->hasMany('Project', ['model' => [Project::class]]);
    }
}

foreach ($client->ref('Project') as $project) {
    echo $project->get('name') . "\n";
}

// $project refers to same object at all times, but $project's active data
// is re-populated on each iteration

$country->addCondition($country->expr('length([name]) = []', [$_GET['len']]));

where length(`name`) = :a

$country->insert('Latvia');

$client->load(3);
$client->ref('Order')->insert($_POST);

$client->addCondition('is_vip');
$client->ref('Order')->insert($_POST);

namespace my;

class User extends \Atk4\Data\Model
{
    public $table = 'user';

    protected function init(): void
    {
        parent::init();

        $this->addField('email');
        $this->addField('name');
        $this->addField('password');

        // add your table fields here
    }
}



 \Atk4\Data\Persistence::connect(PDO_DSN, USER, PASS);
eval(\Psy\sh());

> $m = new \my\User($db);
> $m->loadBy('email', '[email protected]')
> $m->get()
> $m->export(['email', 'name'])
> $m->executeCountQuery()

$query = $connection->dsql();
$query->table('employees')
    ->where('birth_date', '1961-05-02')
    ->field('count(*)');
echo 'Employees born on May 2, 1961: ' . $query->getOne();

// establish a query looking for a maximum salary
$salary = $connection->dsql();

// create few expression objects
$eMs = $salary->expr('max(salary)');
$eDf = $salary->expr('TimeStampDiff(month, from_date, to_date)');

// configure our basic query
$salary
    ->table('salary')
    ->field(['emp_no', 'max_salary' => $eMs, 'months' => $eDf])
    ->group('emp_no')
    ->order('-max_salary')

// define sub-query for employee "id" with certain birth-date
$employees = $salary->dsql()
    ->table('employees')
    ->where('birth_date', '1961-05-02')
    ->field('emp_no');

// use sub-select to condition salaries
$salary->where('emp_no', $employees);

// join with another table for more data
$salary
    ->join('employees.emp_id')
    ->field('employees.first_name');

// finally, fetch result
foreach ($salary as $row) {
    echo 'Data: ' . json_encode($row) . "\n";
}

$ php console.php