组件()函数,把它们设为a美元的产品
财产。但是,让我们允许组件执行查询的工作。
怎么做?组件是服务,这意味着自动装配工作正常。这个例子假设你有一个产品
理论实体和ProductRepository
:
12 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 22
/ / src /组件/ FeaturedProductsComponent.php名称空间应用程序\组件;使用应用程序\存储库\ProductRepository;使用ob娱乐下载\用户体验\TwigComponent\属性\AsTwigComponent;# (AsTwigComponent (featured_products)]类FeaturedProductsComponent{私人ProductRepository$productRepository;公共函数__construct(ProductRepository$productRepository){$这->productRepository =$productRepository;}公共函数getProducts():数组{//返回product数组的示例方法返回$这->productRepository->findFeatured ();}}
在模板中getProducts ()
方法可以通过this.products
:
1 2 3 4 5 6 7 8 9
{/组件/ featured_products.html #模板。树枝#}<div><h3>主打产品h3>{%为积在这里。产品%}...{%endfor%}div>
因为这个组件没有任何我们需要填充的公共属性,你可以用:
1
{{component('featured_products')}}
请注意
因为组件是服务,所以可以使用正常的依赖注入。但是,每个组件服务都注册到共享:假
.这意味着您可以使用不同的数据安全地多次呈现相同的组件,因为每个组件都是一个独立的实例。
在前面的例子中,不是立即查询特色产品(例如在__construct ()
),我们创建了一个getProducts ()
方法,并从模板via中调用this.products
.
这样做是因为,作为一般规则,您应该使您的组件懒惰的尽可能只存储您需要的关于其属性的信息(这也有助于您将组件转换为住组件后)。在此设置中,查询仅在getProducts ()
方法实际被调用。这与框架中的“计算属性”非常相似Vue.
但是没有魔法getProducts ()
方法:如果你打电话this.products
在模板中多次,查询将被多次执行。
让你的getProducts ()
方法的行为类似于真正的计算属性,调用computed.products
在模板中。计算
是一个代理,它包装组件并缓存方法的返回。如果它们被调用额外的次数,则使用缓存的值。
12 3 4 5 6 7 8 9 10 11 12 13 14
{/组件/ featured_products.html #模板。树枝#}<div><h3>主打产品h3>{%为积在计算中。产品%}...{%endfor%}...{%为积在计算中。产品%}{#使用缓存,不会导致第二次查询#}...{%endfor%}div>
请注意
计算方法只适用于没有必需参数的组件方法。
产品
理论实体和ProductRepository
:12 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 22
/ / src /组件/ FeaturedProductsComponent.php名称空间应用程序\组件;使用应用程序\存储库\ProductRepository;使用ob娱乐下载\用户体验\TwigComponent\属性\AsTwigComponent;# (AsTwigComponent (featured_products)]类FeaturedProductsComponent{私人ProductRepository$productRepository;公共函数__construct(ProductRepository$productRepository){$这->productRepository =$productRepository;}公共函数getProducts():数组{//返回product数组的示例方法返回$这->productRepository->findFeatured ();}}
getProducts ()
方法可以通过this.products
:1 2 3 4 5 6 7 8 9
{/组件/ featured_products.html #模板。树枝#}<div><h3>主打产品h3>{%为积在这里。产品%}...{%endfor%}div>
1
{{component('featured_products')}}
请注意
因为组件是服务,所以可以使用正常的依赖注入。但是,每个组件服务都注册到共享:假
.这意味着您可以使用不同的数据安全地多次呈现相同的组件,因为每个组件都是一个独立的实例。
__construct ()
),我们创建了一个getProducts ()
方法,并从模板via中调用this.products
.getProducts ()
方法实际被调用。这与框架中的“计算属性”非常相似Vue.getProducts ()
方法:如果你打电话this.products
在模板中多次,查询将被多次执行。getProducts ()
方法的行为类似于真正的计算属性,调用computed.products
在模板中。计算
是一个代理,它包装组件并缓存方法的返回。如果它们被调用额外的次数,则使用缓存的值。12 3 4 5 6 7 8 9 10 11 12 13 14
{/组件/ featured_products.html #模板。树枝#}<div><h3>主打产品h3>{%为积在计算中。产品%}...{%endfor%}...{%为积在计算中。产品%}{#使用缓存,不会导致第二次查询#}...{%endfor%}div>
请注意
计算方法只适用于没有必需参数的组件方法。