PHP code example of adaiasmagdiel / rubik

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

    

adaiasmagdiel / rubik example snippets


   use AdaiasMagdiel\Rubik\Rubik;

   // SQLite connection
   Rubik::connect([
       'driver' => 'sqlite',
       'path' => 'path/to/database.sqlite'
   ]);

   // MySQL connection
   Rubik::connect([
       'driver' => 'mysql',
       'host' => 'localhost',
       'database' => 'myapp',
       'username' => 'user',
       'password' => 'password',
       'charset' => 'utf8mb4'
   ]);
   

   use AdaiasMagdiel\Rubik\Model;

   class User extends Model
   {
       protected static string $table = 'users';

       protected static function fields(): array
       {
           return [
               'id' => self::Int(autoincrement: true, primaryKey: true),
               'name' => self::Text(notNull: true),
               'email' => self::Text(unique: true, notNull: true),
               'created_at' => self::DateTime(default: 'CURRENT_TIMESTAMP')
           ];
       }
   }
   

   User::createTable(ifNotExists: true);
   

   // Create a new user
   $user = new User();
   $user->name = 'John Doe';
   $user->email = '[email protected]';
   $user->save();

   // Retrieve a user
   $user = User::find(1);
   echo $user->name; // John Doe

   // Update a user
   $user->name = 'Jane Doe';
   $user->save();

   // Delete a user
   $user->delete();
   

$user = new User();
$user->name = 'Alice Smith';
$user->email = '[email protected]';
$user->save(); // Inserts the record into the users table

// Find a user by ID
$user = User::find(1);

// Find all users
$users = User::all();

// Find a user by email
$user = User::findOneBy('email', '[email protected]');

$user = User::find(1);
$user->name = 'Alice Johnson';
$user->save(); // Updates the record

$user = User::find(1);
$user->delete(); // Deletes the record

// Select specific fields with conditions
$users = User::query()
    ->select(['name', 'email'])
    ->where('created_at', '2023-01-01', '>')
    ->orderBy('name', 'ASC')
    ->limit(10)
    ->all();

// Complex query with WHERE IN
$emails = ['[email protected]', '[email protected]'];
$users = User::query()
    ->whereIn('email', $emails)
    ->all();

// Paginate results
$results = User::query()
    ->paginate(page: 1, perPage: 20);

// Paginate results with where clause
$results = User::query()
    ->where('created_at', '2023-01-01', '>')
    ->paginate(page: 1, perPage: 20);

// Update multiple records
User::query()
    ->where('created_at', '2023-01-01', '<')
    ->update(['name' => 'Archived User']);

use AdaiasMagdiel\Rubik\Model;
use AdaiasMagdiel\Rubik\Relationship;

class Post extends Model
{
    protected static string $table = 'posts';

    protected static function fields(): array
    {
        return [
            'id' => self::Int(autoincrement: true, primaryKey: true),
            'user_id' => self::Int(notNull: true),
            'title' => self::Text(notNull: true),
            'content' => self::Text()
        ];
    }

    public function user(): Relationship
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

class User extends Model
{
    // ... fields() as defined earlier

    public function posts(): Relationship
    {
        return $this->hasMany(Post::class, 'user_id');
    }
}

// Create tables
User::createTable(ifNotExists: true);
Post::createTable(ifNotExists: true);

// Create a user and posts
$user = new User();
$user->name = 'Bob';
$user->email = '[email protected]';
$user->save();

$post1 = new Post();
$post1->user_id = $user->id;
$post1->title = 'First Post';
$post1->content = 'Hello, world!';
$post1->save();

$post2 = new Post();
$post2->user_id = $user->id;
$post2->title = 'Second Post';
$post2->content = 'Another post.';
$post2->save();

// Access relationships
$user = User::find(1);
$posts = $user->posts; // Array of Post instances
foreach ($posts as $post) {
    echo $post->title . "\n";
}

$post = Post::find(1);
$user = $post->user; // User instance
echo $user->name; // Bob

$users = [
    ['name' => 'Alice', 'email' => '[email protected]'],
    ['name' => 'Bob', 'email' => '[email protected]'],
    ['name' => 'Charlie', 'email' => '[email protected]']
];
User::insertMany($users);

use AdaiasMagdiel\Rubik\Rubik;
use AdaiasMagdiel\Rubik\Model;

Rubik::connect([
    'driver' => 'sqlite',
    'path' => ':memory:'
]);

// Define and create a model
class Product extends Model
{
    protected static string $table = 'products';

    protected static function fields(): array
    {
        return [
            'id' => self::Int(autoincrement: true, primaryKey: true),
            'name' => self::Text(notNull: true),
            'price' => self::Real(notNull: true),
            'is_active' => self::Boolean(default: true)
        ];
    }
}

Product::createTable();

// Insert a product
$product = new Product();
$product->name = 'Laptop';
$product->price = 999.99;
$product->is_active = true;
$product->save();

// Query products
$products = Product::query()
    ->where('price', 500, '>')
    ->all();
foreach ($products as $product) {
    echo "{$product->name}: \${$product->price}\n";
}

use AdaiasMagdiel\Rubik\Rubik;

Rubik::connect([
    'driver' => 'mysql',
    'host' => 'localhost',
    'database' => 'shop',
    'username' => 'user',
    'password' => 'password',
    'charset' => 'utf8mb4'
]);

// Define and create a model
class Order extends Model
{
    protected static string $table = 'orders';

    protected static function fields(): array
    {
        return [
            'id' => self::Int(autoincrement: true, primaryKey: true),
            'user_id' => self::Int(notNull: true),
            'total' => self::Real(notNull: true),
            'created_at' => self::DateTime(default: 'CURRENT_TIMESTAMP')
        ];
    }
}

Order::createTable(ifNotExists: true);

// Insert an order
$order = new Order();
$order->user_id = 1;
$order->total = 149.99;
$order->save();

// Query orders
$orders = Order::query()
    ->where('total', 100, '>')
    ->orderBy('created_at', 'DESC')
    ->limit(5)
    ->all();
foreach ($orders as $order) {
    echo "Order #{$order->id}: \${$order->total}\n";
}

class Book extends Model
{
    protected static string $table = 'books';

    protected static function fields(): array
    {
        return [
            'id' => self::Int(autoincrement: true, primaryKey: true),
            'title' => self::Text(notNull: true),
            'author' => self::Text(),
            'price' => self::Real(default: 0.0),
            'published' => self::Boolean(default: false)
        ];
    }
}

$book = new Book();
$book->title = 'PHP Essentials';
$book->author = 'Jane Doe';
$book->price = 29.99;
$book->published = true;
$book->save();

$book = Book::find(1);
$book->price = 34.99;
$book->save();

$book->delete();

$users = User::query()
    ->select(['id', 'name'])
    ->where('id', 5, '>')
    ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
    ->groupBy('users.id')
    ->having('COUNT(posts.id) > 0')
    ->orderBy('name', 'ASC')
    ->limit(10)
    ->all();

$res = User::query()
    ->paginate(page: 2, perPage: 10);

$users = $res["data"];
$currentPage = $res["current_page"];
$perPage = $res["per_page"];
$total = $res["total"];
$lastPage = $res["last_page"];

class Comment extends Model
{
    protected static string $table = 'comments';

    protected static function fields(): array
    {
        return [
            'id' => self::Int(autoincrement: true, primaryKey: true),
            'post_id' => self::Int(notNull: true),
            'content' => self::Text(notNull: true)
        ];
    }

    public function post(): Relationship
    {
        return $this->belongsTo(Post::class, 'post_id');
    }
}

class Post extends Model
{
    // ... fields() as defined earlier

    public function comments(): Relationship
    {
        return $this->hasMany(Comment::class, 'post_id');
    }
}

$post = Post::find(1);
$comments = $post->comments; // Array of Comment instances

$comment = Comment::find(1);
$post = $comment->post; // Post instance