Refactoring closures into a trait (or some other structure)

I have a very large form with tonnes of dependant fields, dynamic hints, options etc. The entire form is full of closures and it's getting to a state where it's unweildy. I was wondering if it's possible to refactor the code into a trait or some other file where I can keep the various functions organised. eg. I have the following
->afterStateHydrated(fn(callable $get, callable $set) => $this->hydrateProduct($get, $set))
->afterStateHydrated(fn(callable $get, callable $set) => $this->hydrateProduct($get, $set))
With a public function doing the legwork:
public function hydrateProduct($get = null, $set = null)
{
if ($get('product')) {
$this->product = Product::find($get('product'));
if ($this->product) {
$set('dependant_field', null);
$set('manufacturer', $this->product->manufacturer->id);
$set('price', $this->product->price);
}
}
}
public function hydrateProduct($get = null, $set = null)
{
if ($get('product')) {
$this->product = Product::find($get('product'));
if ($this->product) {
$set('dependant_field', null);
$set('manufacturer', $this->product->manufacturer->id);
$set('price', $this->product->price);
}
}
}
When I move hydrateProduct into a trait though, I get errors, eg: Argument #1 ($get) must be of type callable, null given, called in /private/var/www/vhosts/gunthertore/vendor/livewire/livewire/src/HydrationMiddleware/CallPropertyHydrationHooks.php on line 20 make $get null by default: App\Http\Livewire\Configurator\SectionalDoors::hydrateProduct(): Argument #2 ($set) must be of type callable, Livewire\Request given, called in /private/var/www/vhosts/gunthertore/vendor/livewire/livewire/src/HydrationMiddleware/CallPropertyHydrationHooks.php on line 20 Liverwire\Request? OK: App\Http\Livewire\Configurator\SectionalDoors::hydrateProduct(): Argument #2 ($set) must be of type Livewire\Request, Closure given, called in /private/var/www/vhosts/gunthertore/app/Http/Livewire/Configurator/SectionalDoors.php on line 124 You get the picture. What am I doing wrong? Is this even possible? Is there a better way to separate the functions out than this? Thanks
1 Reply
rominronin
rominronin13mo ago
OK this actually works 100%, the issue I faced was ACTUALLY because the method name I used seems to be used by Filament for something else, changing the name to something else (I used productHydration()) worked as desired.