PHP code example of diego-ninja / granite

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

    

diego-ninja / granite example snippets


$snapshot = Pebble::from($eloquentModel);

$snapshot->name;           // Magic __get
$snapshot['email'];        // ArrayAccess
$snapshot->equals($other); // O(1) fingerprint comparison

use Ninja\Granite\Granite;
use Ninja\Granite\Validation\Attributes\Required;
use Ninja\Granite\Validation\Attributes\Email;
use Ninja\Granite\Validation\Attributes\Min;
use Ninja\Granite\Serialization\Attributes\Hidden;

final readonly class User extends Granite
{
    public function __construct(
        #[Required]
        #[Min(2)]
        public string $name,

        #[Required]
        #[Email]
        public string $email,

        #[Hidden]
        public ?string $password = null,
    ) {}
}

// Create from array
$user = User::from(['name' => 'John Doe', 'email' => '[email protected]', 'password' => 'secret']);

// Create from named parameters
$user = User::from(name: 'John Doe', email: '[email protected]');

// Immutable updates
$updated = $user->with(['name' => 'Jane Doe']);

// Serialization (password hidden automatically)
$json = $user->json();   // {"name":"John Doe","email":"[email protected]"}
$array = $user->array();

// ❌ Deprecated — use Granite instead
final readonly class User extends GraniteVO { }
// ✅
final readonly class User extends Granite { }
bash
php benchmarks/GraniteBench.php
composer bench:objects
composer bench:objects -- --json --iterations=100000 --repetitions=7