Obvious: Mutators & Casting

Introduction

Accessors, mutators, and attribute casting allow you to transform Obvious attribute values when you retrieve or set them on model instances. For example, you may want to use the Framework encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Obvious model. Or, you may want to convert a JSON string that is stored in your database to an array when it is accessed via your Obvious model.

Accessors and Mutators

Framework provides a high-performance architecture for accessors and mutators using Segregated Maps. These maps use O(1) static lookups to resolve closures, completely bypassing the overhead of dynamic method calls and reflection.

Defining Accessors

An accessor transforms an Obvious attribute value when it is accessed. To define accessors, override the segregatedAccessorsMap method on your model. This method should return an array where the keys are attribute names and the values are closures:

<?php

namespace App\Models;

use MacropaySolutions\Kernel\Database\Obvious\Model;

class User extends Model
{
    /**
     * Define the segregated accessors for the model.
     */
    protected function segregatedAccessorsMap(): array
    {
        return [
            'first_name' => fn(?string $value): ?string => $value !== null ? \ucfirst($value) : null,
            'full_name'  => fn(): string => $this->a->first_name . ' ' . $this->a->last_name,
        ];
    }
}

As you can see, the original value of the column is passed to the accessor closure, allowing you to manipulate and return the computed value. To access the value of the accessor, you simply use the a attribute accessor on a model instance:

use App\Models\User;

$user = User::query()->find(1);

$firstName = $user->a->first_name;
$fullName = $user->a->full_name;

[!NOTE]
Closures in segregated maps are automatically bound to the model instance ($this). Do not use static closures!

Defining Mutators

A mutator transforms an Obvious attribute value when it is set. To define mutators, override the segregatedMutatorsMap method. These closures receive the value being set and interact directly with the model’s internal attributes array:

<?php

namespace App\Models;

use MacropaySolutions\Kernel\Database\Obvious\Model;

class User extends Model
{
    /**
     * Define the segregated mutators for the model.
     */
    protected function segregatedMutatorsMap(): array
    {
        return [
            'first_name' => function (?string $value): void {
                $this->attributes['first_name'] = $value !== null ? \strtolower($value) : null;
            },
        ];
    }
}

To use our mutator, we only need to set the first_name attribute via the a accessor on an Obvious model:

use App\Models\User;

$user = User::query()->find(1);

$user->a->first_name = 'Sally';

Attribute Casting

[!WARNING]
Avoid using casts for maximum performance. Native Obvious casting iterates through the casts and executes dynamic type-checking overhead during every single model hydration. For high-speed environments, it is highly recommended to abandon the casts entirely and manually cast your values (e.g., (bool)$value or \json_decode($value, true)) only when needed in your code.

Attribute casting provides functionality similar to accessors and mutators without requiring you to define any additional methods on your model. Instead, your model’s $casts property provides a convenient method of converting attributes to common data types.

The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are:

  • array
  • AsStringable::class
  • boolean
  • collection
  • date
  • datetime
  • immutable_date
  • immutable_datetime
  • decimal:<precision>
  • double
  • encrypted
  • encrypted:array
  • encrypted:collection
  • encrypted:object
  • float
  • hashed
  • integer
  • object
  • real
  • string
  • timestamp

To demonstrate attribute casting, let’s cast the is_admin attribute, which is stored in our database as an integer (0 or 1) to a boolean value:

<?php

namespace App\Models;

use MacropaySolutions\Kernel\Database\Obvious\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

After defining the cast, the is_admin attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:

$user = App\Models\User::query()->find(1);

if ($user->a->is_admin) {
    // ...
}

If you need to add a new, temporary cast at runtime, you may use the mergeCasts method. These cast definitions will be added to any of the casts already defined on the model:

$user->mergeCasts([
    'is_admin' => 'integer',
    'options' => 'object',
]);

[!WARNING]
Attributes that are null will not be cast. In addition, you should never define a cast (or an attribute) that has the same name as a relationship or assign a cast to the model’s primary key.

Stringable Casting

You may use the MacropaySolutions\Kernel\Database\Obvious\Casts\AsStringable cast class to cast a model attribute to a fluent MacropaySolutions\Kernel\Support\Stringable object:

<?php

namespace App\Models;

use MacropaySolutions\Kernel\Database\Obvious\Casts\AsStringable;
use MacropaySolutions\Kernel\Database\Obvious\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'directory' => AsStringable::class,
    ];
}

Array and JSON Casting

The array cast is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Obvious model:

<?php

namespace App\Models;

use MacropaySolutions\Kernel\Database\Obvious\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'options' => 'array',
    ];
}

Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage:

use App\Models\User;

$user = User::query()->find(1);

$options = $user->a->options;

$options['key'] = 'value';

$user->a->options = $options;

$user->save();

To update a single field of a JSON attribute with a more terse syntax, you may make the attribute mass assignable and use the -> operator when calling the update method:

$user = User::query()->find(1);

$user->update(['options->key' => 'value']);

Array Object and Collection Casting

Although the standard array cast is sufficient for many applications, it does have some disadvantages. Since the array cast returns a primitive type, it is not possible to mutate an offset of the array directly. For example, the following code will trigger a PHP error:

$user = User::query()->find(1);

$user->a->options['key'] = $value;

To solve this, Framework offers an AsArrayObject cast that casts your JSON attribute to an ArrayObject class. This feature is implemented using Framework’s custom cast implementation, which allows Framework to intelligently cache and transform the mutated object such that individual offsets may be modified without triggering a PHP error. To use the AsArrayObject cast, simply assign it to an attribute:

use MacropaySolutions\Kernel\Database\Obvious\Casts\AsArrayObject;

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'options' => AsArrayObject::class,
];

Similarly, Framework offers an AsCollection cast that casts your JSON attribute to a Framework Collection instance:

use MacropaySolutions\Kernel\Database\Obvious\Casts\AsCollection;

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'options' => AsCollection::class,
];

If you would like the AsCollection cast to instantiate a custom collection class instead of Framework’s base collection class, you may provide the collection class name as a cast argument:

use App\Collections\OptionCollection;
use MacropaySolutions\Kernel\Database\Obvious\Casts\AsCollection;

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'options' => AsCollection::class.':'.OptionCollection::class,
];

Date Casting

By default, Obvious will cast the created_at and updated_at columns to instances of Carbon, which extends the PHP DateTime class and provides an assortment of helpful methods. You may cast additional date attributes by defining additional date casts within your model’s $casts property array. Typically, dates should be cast using the datetime or immutable_datetime cast types.

When defining a date or datetime cast, you may also specify the date’s format. This format will be used when the model is serialized to an array or JSON:

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'created_at' => 'datetime:Y-m-d',
];

When a column is cast as a date, you may set the corresponding model attribute value to a UNIX timestamp, date string (Y-m-d), date-time string, or a DateTime / Carbon instance. The date’s value will be correctly converted and stored in your database.

You may customize the default serialization format for all of your model’s dates by defining a serializeDate method on your model. This method does not affect how your dates are formatted for storage in the database:

/**
 * Prepare a date for array / JSON serialization.
 */
protected function serializeDate(DateTimeInterface $date): string
{
    return $date->format('Y-m-d');
}

To specify the format that should be used when actually storing a model’s dates within your database, you should define a $dateFormat property on your model:

/**
 * The storage format of the model's date columns.
 *
 * @var string
 */
protected $dateFormat = 'U';

Date Casting, Serialization, and Timezones

By default, the date and datetime casts will serialize dates to a UTC ISO-8601 date string (YYYY-MM-DDTHH:MM:SS.uuuuuuZ), regardless of the timezone specified in your application’s timezone configuration option. You are strongly encouraged to always use this serialization format, as well as to store your application’s dates in the UTC timezone by not changing your application’s timezone configuration option from its default UTC value. Consistently using the UTC timezone throughout your application will provide the maximum level of interoperability with other date manipulation libraries written in PHP and JavaScript.

If a custom format is applied to the date or datetime cast, such as datetime:Y-m-d H:i:s, the inner timezone of the Carbon instance will be used during date serialization. Typically, this will be the timezone specified in your application’s timezone configuration option.

Enum Casting

Obvious also allows you to cast your attribute values to PHP Enums. To accomplish this, you may specify the attribute and enum you wish to cast in your model’s $casts property array:

use App\Enums\ServerStatus;

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'status' => ServerStatus::class,
];

Once you have defined the cast on your model, the specified attribute will be automatically cast to and from an enum when you interact with the attribute:

if ($server->a->status == ServerStatus::Provisioned) {
    $server->a->status = ServerStatus::Ready;

    $server->save();
}

Casting Arrays of Enums

Sometimes you may need your model to store an array of enum values within a single column. To accomplish this, you may utilize the AsEnumArrayObject or AsEnumCollection casts provided by Framework:

use App\Enums\ServerStatus;
use MacropaySolutions\Kernel\Database\Obvious\Casts\AsEnumCollection;

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'statuses' => AsEnumCollection::class.':'.ServerStatus::class,
];

Encrypted Casting

The encrypted cast will encrypt a model’s attribute value using Framework’s built-in encryption features. In addition, the encrypted:array, encrypted:collection, encrypted:object, AsEncryptedArrayObject, and AsEncryptedCollection casts work like their unencrypted counterparts; however, as you might expect, the underlying value is encrypted when stored in your database.

As the final length of the encrypted text is not predictable and is longer than its plain text counterpart, make sure the associated database column is of TEXT type or larger. In addition, since the values are encrypted in the database, you will not be able to query or search encrypted attribute values.

Key Rotation

As you may know, Framework encrypts strings using the key configuration value specified in your application’s app configuration file. Typically, this value corresponds to the value of the APP_KEY environment variable. If you need to rotate your application’s encryption key, you will need to manually re-encrypt your encrypted attributes using the new key.

Query Time Casting

Sometimes you may need to apply casts while executing a query, such as when selecting a raw value from a table. For example, consider the following query:

use App\Models\Post;
use App\Models\User;

$users = User::query()->select([
    'users.*',
    'last_posted_at' => Post::query()->selectRaw('MAX(created_at)')
            ->whereColumn('user_id', 'users.id')
])->get();

The last_posted_at attribute on the results of this query will be a simple string. It would be wonderful if we could apply a datetime cast to this attribute when executing the query. Thankfully, we may accomplish this using the withCasts method:

$users = User::query()->select([
    'users.*',
    'last_posted_at' => Post::query()->selectRaw('MAX(created_at)')
            ->whereColumn('user_id', 'users.id')
])->withCasts([
    'last_posted_at' => 'datetime'
])->get();

Custom Casts

[!WARNING]
Avoid using casts for maximum performance. Native Obvious casting iterates through the casts and executes dynamic type-checking overhead during every single model hydration. For high-speed environments, it is highly recommended to abandon the casts entirely and manually cast your values (e.g., (bool)$value or \json_decode($value, true)) only when needed in your code.

Framework has a variety of built-in, helpful cast types; however, you may occasionally need to define your own cast types. To create a cast, execute the make:cast Run command. The new cast class will be placed in your app/Casts directory:

php run make:cast Json

All custom cast classes implement the CastsAttributes interface. Classes that implement this interface must define a get and set method. The get method is responsible for transforming a raw value from the database into a cast value, while the set method should transform a cast value into a raw value that can be stored in the database. As an example, we will re-implement the built-in json cast type as a custom cast type:

<?php

namespace App\Casts;

use MacropaySolutions\Kernel\Contracts\Database\Obvious\CastsAttributes;
use MacropaySolutions\Kernel\Database\Obvious\Model;

class Json implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  array<string, mixed>  $attributes
     * @return array<string, mixed>
     */
    public function get(Model $model, string $key, mixed $value, array $attributes): array
    {
        return json_decode($value, true);
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  array<string, mixed>  $attributes
     */
    public function set(Model $model, string $key, mixed $value, array $attributes): string
    {
        return json_encode($value);
    }
}

Once you have defined a custom cast type, you may attach it to a model attribute using its class name:

<?php

namespace App\Models;

use App\Casts\Json;
use MacropaySolutions\Kernel\Database\Obvious\Model;

class User extends Model
{
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'options' => Json::class,
    ];
}

Value Object Casting

You are not limited to casting values to primitive types. You may also cast values to objects. Defining custom casts that cast values to objects is very similar to casting to primitive types; however, the set method should return an array of key / value pairs that will be used to set raw, storable values on the model.

As an example, we will define a custom cast class that casts multiple model values into a single Address value object. We will assume the Address value has two public properties: lineOne and lineTwo:

<?php

namespace App\Casts;

use App\ValueObjects\Address as AddressValueObject;
use MacropaySolutions\Kernel\Contracts\Database\Obvious\CastsAttributes;
use MacropaySolutions\Kernel\Database\Obvious\Model;
use InvalidArgumentException;

class Address implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  array<string, mixed>  $attributes
     */
    public function get(Model $model, string $key, mixed $value, array $attributes): AddressValueObject
    {
        return new AddressValueObject(
            $attributes['address_line_one'],
            $attributes['address_line_two']
        );
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  array<string, mixed>  $attributes
     * @return array<string, string>
     */
    public function set(Model $model, string $key, mixed $value, array $attributes): array
    {
        if (!$value instanceof AddressValueObject) {
            throw new InvalidArgumentException('The given value is not an Address instance.');
        }

        return [
            'address_line_one' => $value->lineOne,
            'address_line_two' => $value->lineTwo,
        ];
    }
}

When casting to value objects, any changes made to the value object will automatically be synced back to the model before the model is saved:

use App\Models\User;

$user = User::query()->find(1);

$user->a->address->lineOne = 'Updated Address Value';

$user->save();

[!NOTE]
If you plan to serialize your Obvious models containing value objects to JSON or arrays, you should implement the MacropaySolutions\Kernel\Contracts\Support\Arrayable and JsonSerializable interfaces on the value object.

Value Object Caching

When attributes that are cast to value objects are resolved, they are cached by Obvious. Therefore, the same object instance will be returned if the attribute is accessed again.

If you would like to disable the object caching behavior of custom cast classes, you may declare a public withoutObjectCaching property on your custom cast class:

class Address implements CastsAttributes
{
    public bool $withoutObjectCaching = true;

    // ...
}

Array / JSON Serialization

When an Obvious model is converted to an array or JSON using the toArray and toJson methods, your custom cast value objects will typically be serialized as well as long as they implement the MacropaySolutions\Kernel\Contracts\Support\Arrayable and JsonSerializable interfaces. However, when using value objects provided by third-party libraries, you may not have the ability to add these interfaces to the object.

Therefore, you may specify that your custom cast class will be responsible for serializing the value object. To do so, your custom cast class should implement the MacropaySolutions\Kernel\Contracts\Database\Obvious\SerializesCastableAttributes interface. This interface states that your class should contain a serialize method which should return the serialized form of your value object:

/**
 * Get the serialized representation of the value.
 *
 * @param  array<string, mixed>  $attributes
 */
public function serialize(Model $model, string $key, mixed $value, array $attributes): string
{
    return (string) $value;
}

Inbound Casting

Occasionally, you may need to write a custom cast class that only transforms values that are being set on the model and does not perform any operations when attributes are being retrieved from the model.

Inbound only custom casts should implement the CastsInboundAttributes interface, which only requires a set method to be defined. The make:cast Run command may be invoked with the --inbound option to generate an inbound only cast class:

php run make:cast Hash --inbound

A classic example of an inbound only cast is a “hashing” cast. For example, we may define a cast that hashes inbound values via a given algorithm:

<?php

namespace App\Casts;

use MacropaySolutions\Kernel\Contracts\Database\Obvious\CastsInboundAttributes;
use MacropaySolutions\Kernel\Database\Obvious\Model;

class Hash implements CastsInboundAttributes
{
    /**
     * Create a new cast class instance.
     */
    public function __construct(
        protected string|null $algorithm = null,
    ) {}

    /**
     * Prepare the given value for storage.
     *
     * @param  array<string, mixed>  $attributes
     */
    public function set(Model $model, string $key, mixed $value, array $attributes): string
    {
        return is_null($this->algorithm)
                    ? bcrypt($value)
                    : hash($this->algorithm, $value);
    }
}

Cast Parameters

When attaching a custom cast to a model, cast parameters may be specified by separating them from the class name using a : character and comma-delimiting multiple parameters. The parameters will be passed to the constructor of the cast class:

/**
 * The attributes that should be cast.
 *
 * @var array
 */
protected $casts = [
    'secret' => Hash::class.':sha256',
];

Castables

You may want to allow your application’s value objects to define their own custom cast classes. Instead of attaching the custom cast class to your model, you may alternatively attach a value object class that implements the MacropaySolutions\Kernel\Contracts\Database\Obvious\Castable interface:

use App\ValueObjects\Address;

protected $casts = [
    'address' => Address::class,
];

Objects that implement the Castable interface must define a castUsing method that returns the class name of the custom caster class that is responsible for casting to and from the Castable class:

<?php

namespace App\ValueObjects;

use MacropaySolutions\Kernel\Contracts\Database\Obvious\Castable;
use App\Casts\Address as AddressCast;

class Address implements Castable
{
    /**
     * Get the name of the caster class to use when casting from / to this cast target.
     *
     * @param  array<string, mixed>  $arguments
     */
    public static function castUsing(array $arguments): string
    {
        return AddressCast::class;
    }
}

When using Castable classes, you may still provide arguments in the $casts definition. The arguments will be passed to the castUsing method:

use App\ValueObjects\Address;

protected $casts = [
    'address' => Address::class.':argument',
];

Castables & Anonymous Cast Classes

By combining “castables” with PHP’s anonymous classes, you may define a value object and its casting logic as a single castable object. To accomplish this, return an anonymous class from your value object’s castUsing method. The anonymous class should implement the CastsAttributes interface:

<?php

namespace App\ValueObjects;

use MacropaySolutions\Kernel\Contracts\Database\Obvious\Castable;
use MacropaySolutions\Kernel\Contracts\Database\Obvious\CastsAttributes;
use MacropaySolutions\Kernel\Database\Obvious\Model;

class Address implements Castable
{
    // ...

    /**
     * Get the caster class to use when casting from / to this cast target.
     *
     * @param  array<string, mixed>  $arguments
     */
    public static function castUsing(array $arguments): CastsAttributes
    {
        return new class implements CastsAttributes
        {
            public function get(Model $model, string $key, mixed $value, array $attributes): Address
            {
                return new Address(
                    $attributes['address_line_one'],
                    $attributes['address_line_two']
                );
            }

            public function set(Model $model, string $key, mixed $value, array $attributes): array
            {
                return [
                    'address_line_one' => $value->lineOne,
                    'address_line_two' => $value->lineTwo,
                ];
            }
        };
    }
}

This site uses Just the Docs, a documentation theme for Jekyll.