kodooy/name-value-object

A Laravel package for handling name value objects and database casting

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/kodooy/name-value-object

v1.0.0 2025-10-02 13:47 UTC

This package is auto-updated.

Last update: 2026-01-02 14:45:22 UTC


README

A Laravel package for handling name value objects and database casting.

Requirements

  • PHP 8.2 or higher
  • Laravel 10.0, 11.0, or 12.0

Installation

composer require kodooy/name-value-object

Usage

Database Casting

Your database table should have first_name and last_name columns:

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

Add the cast to your Eloquent model:

use Kodooy\NameValueObject\Casts\Name;

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

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

Usage:

use Kodooy\NameValueObject\ValueObjects\Name;

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

In controller:

use Kodooy\NameValueObject\ValueObjects\Name;

class UsersController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'first_name' => ['required', 'string', 'max:100'],
            'last_name'  => ['required', 'string', 'max:100'],
            'email'      => ['required', 'email', 'unique:users,email'],
        ]);

        $user = User::create([
            'name' => new Name(
                $validated['first_name'],
                $validated['last_name']
            ),
            'email' => $validated['email'],
        ]);

        // ...
    }
}

The name is automatically cast when retrieved:

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'

API Reference

Name Value Object

The Name value object provides the following methods:

Constructor

new Name(string $firstName, string $lastName)

Creates a new Name instance. Both parameters are required and cannot be empty.

  • Parameters:
    • $firstName: The first name (will be trimmed and capitalized)
    • $lastName: The last name (will be trimmed and capitalized)
  • Throws: InvalidArgumentException if either name is empty

Basic Access Methods

$name->first(): string

Returns the first name.

$name->last(): string

Returns the last name.

$name->full(): string

Returns the full name (first name + space + last name).

Formatting Methods

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

Returns the initials with optional separator.

  • Examples: initials() → "JD", initials('.') → "J.D.", initials('-') → "J-D"
$name->monogram(): string

Returns the monogram format with periods.

  • Example: "J.D."
$name->formal(): string

Returns the name in formal format (Last, First).

  • Example: "Doe, John"
$name->casual(): string

Returns the casual format (First + Last initial).

  • Example: "John D."
$name->abbreviated(): string

Returns the abbreviated format (First initial + Last name).

  • Example: "J. Doe"
$name->reverse(): string

Returns the reversed format (Last + First).

  • Example: "Doe John"

Variation Methods

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

Returns the name with a prefix.

  • Examples: withPrefix('Dr.') → "Dr. John Doe", withPrefix('Mr.') → "Mr. John Doe"
$name->withSuffix(string $suffix): string

Returns the name with a suffix.

  • Examples: withSuffix('Jr.') → "John Doe Jr.", withSuffix('III') → "John Doe III"

Privacy Methods

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

Returns a masked version of the name.

  • Parameters:
    • $visibleChars: Number of visible characters from the start (default: 1)
    • $maskChar: Character to use for masking (default: '*')
  • Example: masked() → "J*** D***", masked(2, '#') → "Jo## Do#"
$name->obfuscated(): string

Returns a SHA256 hash of the full name for privacy.

  • Example: "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"

Comparison Methods

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

Checks if this name is equal to another Name instance.

  • Performs case-sensitive comparison of both first and last names

Data Conversion Methods

$name->toArray(): array

Returns an array representation containing:

  • first_name: The first name
  • last_name: The last name
  • full_name: The full name
  • initials: The initials
$name->__toString(): string

Returns the full name. Allows the object to be used as a string.

  • Example: echo $name; // "John Doe"

Static Factory Methods

Name::fromArray(array $data): Name

Creates a Name instance from an array.

  • Accepted keys: first_name/firstname and last_name/lastname
  • Throws: InvalidArgumentException if required keys are missing
Name::fromFullName(string $fullName): Name

Creates a Name instance from a full name string.

  • Parameter: $fullName - Must contain exactly two words separated by space
  • Throws: InvalidArgumentException if format is invalid
  • Example: fromFullName('John Doe') → Name('John', 'Doe')
Name::fromEmail(string $email): Name

Creates a Name instance from an email address.

  • Parameter: $email - Must be in format "first.last@domain.com"
  • Throws: InvalidArgumentException if email format is invalid
  • Example: fromEmail('john.doe@example.com') → Name('John', 'Doe')
Name::random(): Name

Generates a random Name instance from predefined lists.

  • Returns a Name with randomly selected first and last names

Usage Examples

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

Error Handling

Invalid Data Handling

The Name value object validates input and throws exceptions for invalid data:

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."
}

Controller Validation

Proper validation in your controller prevents exceptions:

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' => ['required', 'string', 'min:1', 'max:100'],
            'last_name'  => ['required', 'string', 'min:1', 'max:100'],
            'email'      => ['required', 'email', 'unique:users,email'],
        ]);

        try {
            $user = User::create([
                'first_name' => $validated['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);
    }
}

Cast Error Handling

When using the cast with invalid data types:

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

Testing

composer test

License

The MIT License (MIT). Please see License File for more information.