You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I recently had a pretty sneaky bug. Given this code:
finalclassSomeFactoryextendsPersistentObjectFactory
{
protectedfunctioninitialize(): static
{
return$this->beforeInstantiate(
function (array$attributes): array {
if ($this->isPersisting()) {
// do some stuff which interacts with db
} else {
// do some stuff without db
}
return$attributes;
}
);
}
}
// in some test:SomeFactory::new()->withoutPersisting()->create();
We're entering in the if() because $this here represents the factory returned by SomeFactory::new() and not the last instance on which we call create(). This is really unlucky, I had hard time to figure what was going on...
My first guess to fix this was to bind the closure to the actual instance used in create():
// SomeFactorypublicfunctioncreate(callable|array$attributes = []): object
{
// ...foreach ($this->beforeInstantiateas$hook) {
try {
$hook = \Closure::fromCallabale($hook)->bindTo($this);
} catch(\Exception) {
// the closure is static and cannot be bound to anything
}
$parameters = $hook($parameters, static::class());
// ...
}
}
it works nicely, but it would not work outside from a factory, so this is a no-go.
Another solution would be to the current factory as a new parameter to all our hooks:
I recently had a pretty sneaky bug. Given this code:
We're entering in the
if()
because$this
here represents the factory returned bySomeFactory::new()
and not the last instance on which we callcreate()
. This is really unlucky, I had hard time to figure what was going on...My first guess to fix this was to bind the closure to the actual instance used in
create()
:it works nicely, but it would not work outside from a factory, so this is a no-go.
Another solution would be to the current factory as a new parameter to all our hooks:
WDYT?
The text was updated successfully, but these errors were encountered: