Ahmed essam
Ahmed essam

Reputation: 357

Laravel reusable functions

I am using Repository design pattern and I have a function generateBarcode() this function just do some logic and insert data in database.

I am calling this function in more one function and more that one repository to generate a new Barcode.

Question is:

What is the best way to make this function reusable?

  1. Helpers

But I don't think this is a good idea since it am dealing with database.

  1. Events

Firing event and storing the result. $barcode = event(new NewBarcodeRequired())

That what I am doing right now and data is returned as an array

Also I don't think that is a good idea because I have read that events shouldn't return data.

  1. Repository

Create a new repository for this function but I think it is a very bad idea because I won't create a class for every reusable function that I have.

Upvotes: 0

Views: 1790

Answers (1)

Anar Bayramov
Anar Bayramov

Reputation: 11594

Traits could be a good option for this case. Which will give you flexibility to use in any of your class without requirement of class extension.

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.

http://php.net/manual/en/language.oop5.traits.php

Upvotes: 1

Related Questions