Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Utilities file in php?

Tags:

oop

php

utilities

What is the best way to deal with "utility" functions in a OOP PHP framework? Right now, we just have a file with several functions that are needed throughout the system. (For example, a distribute() function which accepts a value and an array, and returns an array with the value distributed in the same proportions and same keys as the input array.)

I have always felt "dirty" using that because it's not object-oriented at all. Is it better practice to move these into various classes as static methods, or is that just a semantic workaround? Or is there just going to be a level in a framework where some stuff is going to fall outside of the OOP structure?

like image 320
keithjgrant Avatar asked Nov 19 '09 19:11

keithjgrant


2 Answers

I tend to make a Util() class that contains only static methods, has no attributes, and is not inherited from. Essentially, it acts as a "namespace" to a bunch of utility functions. I will allow this class to grow in size, but will occasionally split of methods into their own classes if it is clear that those methods are designed only to work with certain kinds of data or if it is clear that a group of related methods should be grouped into a class along with, perhaps, some attributes.

I think it's perfectly OK to deviate from purely OOP practices so long as the code that deviates is well-organized and is not creating architectural flaws in your system that make it harder to understand and maintain.

like image 166
jkndrkn Avatar answered Sep 27 '22 21:09

jkndrkn


I've always been more pragmatic about questions like these.

If you want to go full-OOP, you should obviously stick these into classes. However, these classes are only going to be container classes, because they don't really represent objects of any kind.

Also: using classes would require you to either have an instance of that class, using the singleton pattern or declaring every function static. The first one is slower (okay, might not be that much, but in a large framework things like that get large, too - especially in interpreted languages like PHP), while the second and third ones are just plain useless and simply an OOP wrapper for a set of functions (especially the third approach).

EDIT: Feel free to prove me wrong. I might be. I'm not too experienced and always saw it that way, but I might be wrong.

like image 38
Franz Avatar answered Sep 27 '22 22:09

Franz