PHP code example of initorm / orm
1. Go to this page and download the library: Download initorm/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/ */
initorm / orm example snippets
InitORM\Database\Facade\DB;
DB::createImmutable([
'dsn' => 'mysql:host=localhost;dbname=app;charset=utf8mb4',
'username' => 'app',
'password' => 'secret',
]);
namespace App\Model;
class Posts extends \InitORM\ORM\Model
{
protected string $schema = 'posts';
protected string $schemaId = 'id';
protected bool $useSoftDeletes = true;
protected ?string $createdField = 'created_at';
protected ?string $updatedField = 'updated_at';
protected ?string $deletedField = 'deleted_at';
protected string $entity = \App\Entity\PostEntity::class;
}
namespace App\Entity;
class PostEntity extends \InitORM\ORM\Entity
{
public function getTitleAttribute(mixed $value): mixed
{
return is_string($value) ? ucwords($value) : $value;
}
public function setTitleAttribute(mixed $value): void
{
// ALWAYS use setAttribute() inside a mutator —
// $this->title = ... bypasses __set and creates a dynamic property.
$this->setAttribute('title', is_string($value) ? trim($value) : $value);
}
}
use App\Model\Posts;
$posts = new Posts();
// Create
$posts->create(['title' => 'My First Post', 'body' => 'Hello world']);
// Read (returns a DataMapper hydrating PostEntity instances)
foreach ($posts->read()->rows() as $entity) {
echo $entity->title; // accessor runs here
}
// Update by primary key (lifted out of $set into a WHERE)
$posts->update(['id' => 5, 'title' => 'Edited']);
// Soft delete (sets deleted_at), then permanently purge
$posts->delete(['id' => 5]);
$posts->delete(['id' => 5], purge: true);
$entities = $posts
->where('status', '=', 'published')
->orderBy('id', 'DESC')
->limit(10)
->read()
->rows();
$posts->delete(['id' => 5], purge: true);
foreach ($posts->onlyDeleted()->read()->rows() as $deleted) {
// …
}
class PostEntity extends \InitORM\ORM\Entity
{
public function getPostTitleAttribute(mixed $value): mixed
{
return ucwords((string) $value);
}
public function setPostTitleAttribute(mixed $value): void
{
$this->setAttribute('post_title', strtolower((string) $value));
}
}
class ReadOnlyConfig extends \InitORM\ORM\Model
{
protected string $schema = 'configuration';
protected bool $writable = false;
protected bool $updatable = false;
protected bool $deletable = false;
}
(new ReadOnlyConfig())->create([...]); // throws WritableException
class ReportsModel extends \InitORM\ORM\Model
{
protected string $schema = 'events';
protected ?array $credentials = [
'dsn' => 'pgsql:host=reports.internal;dbname=reports',
'username' => 'reports_ro',
'password' => '…',
'driver' => 'pgsql',
];
}