My problem was that I used class instances in custom config files.
To solve this I came up with this PHP trait that makes a class with public properties serializable. (works on read-only classes as well)
<?php
namespace App;
/**
* Adds __set_state for proper serialization in config caching.
*
* Use in classes with public properties and matching constructor params.
*/
trait Serializable
{
public static function __set_state(array $array)
{
return new static(...$array);
}
}
Example
<?php
namespace App;
readonly class Plan
{
use Serializable;
public function __construct(
public string $name,
public PlanSlugEnum $slug,
<?php
// config/myapp/plans.php
use App\{Plan, PlanSlugEnum};
return [
new Plan(
name : 'Free',
slug : PlanSlugEnum::FREE,
stripeId : null,
dataLimitGB : 1,
requestsPerMinute: 10,
),
new Plan(
name : 'Starter Monthly',
slug : PlanSlugEnum::STARTER_MONTHLY,