Styphon
Styphon

Reputation: 10447

Sharing functions across unrelated classes

I'm still working my head around object orientated programming and getting away from procedural programming. Although I use classes I know I still don't write my code fully OOP. I've been reading and doing my best to get as much information and practice as I can to further my abilities and I'm making progress, but one area that I'm currently confused on is how to deal with an independent function that would be reused across multiple classes that are entirely unrelated.

I understand I can extend classes, or implement an interface, or use a trait. I found this post, which was very helpful in clarifying things, however I'm still confused what is the correct method to use in this situation. For example, I have a function that will generate a random alphanumeric string to a length specified by an input, and will return that string. Several classes, not related, can use this function and it makes no sense to include the function in each class.

To me the most obvious thing is a library of common functions in a trait, which I can then just use in a class as needed. However is this the proper way to do things?

Upvotes: 4

Views: 1482

Answers (2)

Gordon
Gordon

Reputation: 316969

For example, I have a function that will generate a random alphanumeric string to a length specified by an input, and will return that string. Several classes, not related, can use this function and it makes no sense to include the function in each class.

It's not a function. It's a responsibility. A good rule of thumb is to forget functions exist when doing OOP. Your function is a class RandomAlphanumericStringGenerator. It has one method generate that accepts $length as an input, which will generate and return the string. Create an instance of that Generator and inject it to objects that have need for this.

Upvotes: 0

gd1
gd1

Reputation: 11403

Yes, absolutely.

You don't need traits for utilities, just make a library. If you want to be tidy and stick to the object-oriented paradigm, create utility classes that group several static methods performing similar tasks - instead of creating large PHP files containing a bunch of functions that pollute the global scope.

Upvotes: 2

Related Questions