PHP code example of nixphp / orm

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

    

nixphp / orm example snippets


return [
    // ...
    'database' => [
        'driver'   => 'mysql',
        'host'     => '127.0.0.1',
        'database' => 'myapp',
        'username' => 'root',
        'password' => '',
        'charset'  => 'utf8mb4',
    ]
];

return [
    // ...
    'database' => [
        'driver'   => 'sqlite',
        'database' => __DIR__ . '/../storage/database.sqlite',
    ]
];

return [
    // ...
    'database' => [
        'driver'   => 'sqlite',
        'database' => ':memory:',
    ]
];

class Product extends AbstractModel
{
    protected ?int $id = null;
    protected string $name = '';
    protected ?Category $category = null;
    protected array $tags = [];

    public function getTags(): array
    {
        if ($this->tags === []) {
            $this->tags = (new TagRepository())->findByPivot(Product::class, $this->id);
        }
        return $this->tags;
    }

    public function getCategory(): ?Category
    {
        if ($this->category === null && $this->category_id) {
            $this->category = (new CategoryRepository())->findOneBy('id', $this->category_id);
        }
        return $this->category;
    }
}

$category = (new CategoryRepository())->findOrCreateByName('Books');
$tagA     = (new TagRepository())->findOrCreateByName('Bestseller');
$tagB     = (new TagRepository())->findOrCreateByName('Limited');

$product = new Product();
$product->name = 'NixPHP for Beginners';
$product->addCategory($category);
$product->addTag($tagA);
$product->addTag($tagB);

em()->save($product);

$product = (new ProductRepository())->findOneBy('id', 1);

echo $product->name;
print_r($product->getCategory());
print_r($product->getTags());