Laravel 可重复使用的函数
Laravel reusable functions
我正在使用存储库设计模式并且我有一个函数generateBarcode()
这个函数只是做一些逻辑并在数据库中插入数据。
我在多个函数和多个存储库中调用此函数以生成新条形码。
Question is:
使此功能可重用的最佳方法是什么?
- 帮手
但我不认为这是一个好主意,因为它正在处理数据库。
- 事件
触发事件并存储结果。
$barcode = event(new NewBarcodeRequired())
我现在正在做的事情和数据被return编辑为数组
我也不认为这是个好主意,因为我读过事件不应该 return 数据。
- 存储库
为这个函数创建一个新的存储库,但我认为这是一个非常糟糕的主意,因为我不会为我拥有的每个可重用函数创建一个 class。
对于这种情况,Traits 可能是一个不错的选择。这将使您可以灵活地在任何 class 中使用而无需 class 扩展名。
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
A Trait is similar to a class, but only intended to group
functionality in a fine-grained and consistent way. It is not possible
to instantiate a Trait on its own. It is an addition to traditional
inheritance and enables horizontal composition of behavior; that is,
the application of class members without requiring inheritance.
我正在使用存储库设计模式并且我有一个函数generateBarcode()
这个函数只是做一些逻辑并在数据库中插入数据。
我在多个函数和多个存储库中调用此函数以生成新条形码。
Question is:
使此功能可重用的最佳方法是什么?
- 帮手
但我不认为这是一个好主意,因为它正在处理数据库。
- 事件
触发事件并存储结果。
$barcode = event(new NewBarcodeRequired())
我现在正在做的事情和数据被return编辑为数组
我也不认为这是个好主意,因为我读过事件不应该 return 数据。
- 存储库
为这个函数创建一个新的存储库,但我认为这是一个非常糟糕的主意,因为我不会为我拥有的每个可重用函数创建一个 class。
Traits 可能是一个不错的选择。这将使您可以灵活地在任何 class 中使用而无需 class 扩展名。
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.
A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.