PHP code example of kodooy / name-value-object

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

    

kodooy / name-value-object example snippets


Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('first_name');
    $table->string('last_name');
    $table->timestamps();
});

use Kodooy\NameValueObject\Casts\Name;

class User extends Model
{
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
    ];

    protected $casts = [
        'name' => Name::class,
    ];
}

use Kodooy\NameValueObject\ValueObjects\Name;

$user = new User();
$user->name = new Name('John', 'Doe');
$user->save();

use Kodooy\NameValueObject\ValueObjects\Name;

class UsersController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'first_name' => ['
                $validated['first_name'],
                $validated['last_name']
            ),
            'email' => $validated['email'],
        ]);

        // ...
    }
}

echo $user->name->full();     // 'John Doe'
echo $user->name->first();    // 'John'
echo $user->name->last();     // 'Doe'
echo $user->name->initials(); // 'JD'
echo $user->name;             // 'John Doe'

new Name(string $firstName, string $lastName)

$name->first(): string

$name->last(): string

$name->full(): string

$name->initials(string $separator = ''): string

$name->monogram(): string

$name->formal(): string

$name->casual(): string

$name->abbreviated(): string

$name->reverse(): string

$name->withPrefix(string $prefix): string

$name->withSuffix(string $suffix): string

$name->masked(int $visibleChars = 1, string $maskChar = '*'): string

$name->obfuscated(): string

$name->equals(Name $other): bool

$name->toArray(): array

$name->__toString(): string

Name::fromArray(array $data): Name

Name::fromFullName(string $fullName): Name

Name::fromEmail(string $email): Name

Name::random(): Name

use Kodooy\NameValueObject\ValueObjects\Name;

// Creating a name
$name = new Name('john', 'doe');

// Accessing properties
echo $name->first();    // 'John' (auto-capitalized)
echo $name->last();     // 'Doe' (auto-capitalized)
echo $name->full();     // 'John Doe'
echo $name->initials(); // 'JD'
echo $name;             // 'John Doe' (via __toString)

// Array operations
$array = $name->toArray();
// ['first_name' => 'John', 'last_name' => 'Doe', 'full_name' => 'John Doe', 'initials' => 'JD']

$name2 = Name::fromArray(['first_name' => 'Jane', 'last_name' => 'Smith']);

// Comparison
$areEqual = $name->equals($name2); // false

use Kodooy\NameValueObject\ValueObjects\Name;
use InvalidArgumentException;

// This will throw InvalidArgumentException
try {
    $name = new Name('', 'Doe'); // Empty first name
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // "First name cannot be empty."
}

try {
    $name = new Name('John', ''); // Empty last name
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // "Last name cannot be empty."
}

try {
    $name = new Name('   ', 'Doe'); // Whitespace-only first name
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // "First name cannot be empty."
}

use Kodooy\NameValueObject\ValueObjects\Name;
use Illuminate\Http\Request;
use InvalidArgumentException;

class UsersController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'first_name' => ['           'last_name'  => $validated['last_name'],
                'email'      => $validated['email'],
            ]);

            // Access the name cast safely
            $fullName = $user->name->full();

        } catch (InvalidArgumentException $e) {
            // Handle unexpected validation bypass
            return response()->json(['error' => 'Invalid name data'], 422);
        }

        return response()->json($user);
    }
}

use Kodooy\NameValueObject\ValueObjects\Name;
use InvalidArgumentException;

$user = new User();

try {
    // This will throw InvalidArgumentException
    $user->name = 'Just a string'; // Must be Name instance
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(); // "Value must be an instance of Name."
}

// Correct usage
$user->name = new Name('John', 'Doe'); // Works correctly