jessarcher / laravel-castable-data-transfer-object

Automatically cast JSON columns to rich PHP objects in Laravel using Spatie's data-transfer-object class
https://jessarcher.com/blog/casting-json-columns-to-value-objects/
MIT License
328 stars 23 forks source link

Specifying default value via the config file #17

Closed hcivelek closed 2 years ago

hcivelek commented 2 years ago

Hi, I want to thank you first for this package. is it possible to specify some default values in the cast via the config file?

When I tried like:

namespace App\Values;

use JessArcher\CastableDataTransferObject\CastableDataTransferObject;

class LibraryConf extends CastableDataTransferObject
{
    public int $minDeliveryDays = config('preferences.min_delivery_days');
    public int $maxDeliveryDays = config('preferences.max_delivery_days');
    public int $maxLoanLimit = config('preferences.max_loan_limit');
}

I got:

Constant expression contains invalid operations

I understand that is not a Laravel or this package's problem, it is PHP's problem, but is there any way to get around it? Or writing some defaults on the class directly is not a big deal?

jessarcher commented 2 years ago

I'd just put the defaults on the DTO class.

Alternatively, you could probably add a constructor something like this (untested):

class LibraryConf extends CastableDataTransferObject
{
    // ...

    public function __construct(array $arguments)
    {
        $arguments['minDeliveryDays'] ??= config('preferences.min_delivery_days');

        parent::__construct($arguments);
    }
}

Hope that helps!