@@ -360,8 +360,12 @@ need to populate, you can render it with:
360360 means that you can safely render the same component multiple times with
361361 different data because each component will be an independent instance.
362362
363- Computed Properties
364- ~~~~~~~~~~~~~~~~~~~
363+ Computed Methods
364+ ~~~~~~~~~~~~~~~~
365+
366+ .. versionadded :: 2.1
367+
368+ Computed Methods were added in TwigComponents 2.1.
365369
366370In the previous example, instead of querying for the featured products
367371immediately (e.g. in ``__construct() ``), we created a ``getProducts() ``
@@ -378,35 +382,32 @@ But there's no magic with the ``getProducts()`` method: if you call
378382``this.products `` multiple times in your template, the query would be
379383executed multiple times.
380384
381- To make your ``getProducts() `` method act like a true computed property
382- (where its value is only evaluated the first time you call the method),
383- you can store its result on a private property:
385+ To make your ``getProducts() `` method act like a true computed property,
386+ call ``computed.products `` in your template. ``computed `` is a proxy
387+ that wraps your component and caches the return of methods. If they
388+ are called additional times, the cached value is used.
384389
385- .. code-block :: diff
390+ .. code-block :: twig
386391
387- // src/Components/FeaturedProductsComponent.php
388- namespace App\Components;
389- // ...
392+ {# templates/components/featured_products.html.twig #}
390393
391- #[AsTwigComponent('featured_products')]
392- class FeaturedProductsComponent
393- {
394- private ProductRepository $productRepository;
394+ <div>
395+ <h3>Featured Products</h3>
395396
396- + private ?array $products = null;
397+ {% for product in computed.products %}
398+ ...
399+ {% endfor %}
397400
398- // ...
401+ ...
402+ {% for product in computed.products %} {# use cache, does not result in a second query #}
403+ ...
404+ {% endfor %}
405+ </div>
399406
400- public function getProducts(): array
401- {
402- + if ($this->products === null) {
403- + $this->products = $this->productRepository->findFeatured();
404- + }
407+ .. note ::
405408
406- - return $this->productRepository->findFeatured();
407- + return $this->products;
408- }
409- }
409+ Computed methods only work for component methods with no required
410+ arguments.
410411
411412Component Attributes
412413--------------------
0 commit comments