Sharing functions between unrelated classes

I am still working on object oriented programming and avoid procedural programming. Although I use classes, I know that I still don't write my code entirely OOP. I have read and done my best to get as much information and practice as possible to advance my abilities and I am moving forward, but one area I am confused about right now is how to deal with an independent function that is reusable by multiple classes that are completely unrelated.

I understand that I can extend classes, implement an interface, or use a trait. I found this post to be very helpful in figuring things out, however I am still confused as to which is the correct method to use in this situation. For example, I have a function that will generate a random alphanumeric string up to the length given by the input and will return that string. Multiple unrelated classes can use this feature, and it doesn't make sense to include the feature in every class.

For me, the most obvious thing is a library of common functions in a trait, which I can then simply use in the class as needed. However, is this the correct way to do something?

+3


source to share


2 answers


Yes, absolutely.



You don't need traits for utilities, just create a library. If you want to be neat and stick to an object-oriented paradigm, create utility classes that group multiple methods static

that perform similar tasks, instead of creating large PHP files containing many functions that pollute the global scope.

+2


source


For example, I have a function that will generate a random alphanumeric string up to the length given by the input and will return that string. Multiple unrelated classes can use this feature, and it doesn't make sense to include the feature in every class.



This is not a function. This is responsibility . A good rule of thumb is to forget about the features that exist when doing OOP. Your function is a class RandomAlphanumericStringGenerator

. It has one method generate

, which takes $length

as input, which will generate and return a string. Instantiate this Generator and inject it into the objects that need it .

0


source







All Articles