I’d like to better understand Composers and how they should be used. More specifically, I’ve noticed that if my composer targets views matched by 'x' (ie. all views), then the functions within that composer get called multiple times, once per view. So if a page has a large number of subviews, these functions get called a large number of times.
In the sage starter project, there exists a composer by default called ‘App’ that targets all views. Is this wise? I can’t think of a situation where you would want to target all views with a Composer, and have potentially heavy functions run more than necessary?
If you’re worried about repeatedly accessing certain things that return same value, you can implement a caching system that only persists within a single request.
There are many examples of how to do this, but the easiest way is to use Laravel Blink from Spatie, it should help you in this case.
I wouldn’t recommend using the WP Object Cache if your functions return different values depending on arguments and you’re planning to use persistent cache plugins in production.
Thanks @niznet, looks like a great resource I will be sure to check out.
So it sounds like there is no built-in functionality to cache output from Composers? Am I correct in thinking that if I put computationally-expensive code in a Composer that targets all views (*), it will get run multiple times - once for each view? Perhaps I need to use more Composers and specify their views more strictly!
I don’t delve deeper into acorn code, but I assume it should be similar to Laravel view composer, and acorn simply wraps them around to streamline theme development, so I believe no such thing is implemented.
Yes, you’re correct. The Illuminate\View\View::renderContents() function is responsible for triggering the composer linked to a view. So whenever a view is rendered, regardless of whether it involves Blade template inheritance or simple @include statements, this method is executed, triggering any composer bound to that view.
If your composer uses * to bind all views and your page renders 5 views, it will be executed 5 times.