PHP code example of phpfui / orm

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

    

phpfui / orm example snippets


$pdo = new \PHPFUI\ORM\PDOInstance($yourConnectionString);
// permform any custom configuration settings needed on $pdo
\PHPFUI\ORM::addConnection($pdo);

$book = new \App\Record\Book();
$book->title = 'PHP ORM: The Right Way';
$book->price = 24.99;

$author = new \App\Record\Author();
$author->name = 'Bruce Wells';

$book->author = $author;  // Save the author
$book->save();            // Save the book

$bookTable = new \App\Table\Book();
$bookTable->setWhere(new \PHPFUI\ORM\Condition('title', '%orm%', new \PHPFUI\ORM\Operator\Like()));
$bookTable->join('author');

foreach ($bookTable->getDataObjectCursor() as $book)
  {
  echo "{$book->title} by {$book->name} is $ {$book->price}\n";
  }

// discount all PHP books to 19.99
$bookTableUpdater = new \App\Table\Book();
$bookTableUpdater->setWhere(new \PHPFUI\ORM\Condition('title', '%PHP%', new \PHPFUI\ORM\Operator\Like()));
$bookTableUpdater->update(['price' => 19.99]);

foreach ($bookTableUpdater->getRecordCursor() as $book)
  {
  echo "{$book->title} by {$book->author->name} is now $ {$book->price}\n";
  }

$book->title = 'This title is way to long for the database and will return a validation error. We should write a migration to make it varchar(255)!';
$errors = $book->validate();
foreach ($errors as $field => $fieldErrors)
  {
  echo "Field {$field} has the following errors:\n";
  foreach ($fieldErrors as $error)
    {
    echo $error . "\n";
    }
  }

namespace App\Migration;

class Migration_1 extends \PHPFUI\ORM\Migration
  {

  public function description() : string
    {
    return 'Lengthen book.title field to 255';
    }

  public function up() : bool
    {
    return $this->alterColumn('book', 'title', 'varchar(255) not null');
    }

  public function down() : bool
    {
    return $this->alterColumn('book', 'title', 'varchar(50) not null');
    }
  }

// get the current connection just for fun
$currentConnection = \PHPFUI\ORM::getConnection();

$cursors = [];
// getRecordCursor will bind the cursor to the current database instance
$cursors[] = (new \App\Table\Author())->getRecordCursor();
$cursors[] = (new \App\Table\Book())->getRecordCursor();

// set up a new database connection
$pdo = new \PDO($newConnectionString);
$newConnectionId = \PHPFUI\ORM::addConnection($pdo);

foreach ($cursors as $cursor)
  {
  foreach ($cursor as $record)
    {
    $record->insert();	// insert into new database ($newConnectionId)
    }
  }
// back to the original database
\PHPFUI\ORM::useConnection($currentConnection);