deebow's avatar

Correct way of executing array of invokable classes

First of all, I'm a Laravel newbie, and feel free to roast what I did :D

Before getting to my main question, here’s the context: the app uses a lot of invokable action classes, and they’re executed like this: app(SomeActionClass::class)($data)

So here are my questions:

  1. If these invokable classes don’t have any dependencies, why call them using app() instead of the classic (new SomeActionClass)($data)?

  2. Regarding the code below, did I even do the right thing just to run a series of invokable validator classes?

private function validators(): array
{
	return [
		fn () => app(ValidatorOne::class),
  		fn () => app(ValidatorTwo::class),
		...
		...
	];
}

// and called this way
$data = new MyData(...);

foreach ($this->validators() as $validator) {
	$validator()($data);
}

So the follow-up questions for #2 are:

  1. Is this even a good way to execute each validators, or am I just overcomplicating it?
  2. Is calling app() for every invokable class excessive?
  3. What would you personally recommend as the best approach?

Edit: It seems that my post lack context, but one of my goal really is to establish testability, so I can easily mock each of these validations. But if someone could suggest a better approach to this, then it would be greatly appreciated :)

0 likes
4 replies

Please or to participate in this conversation.