Where to store helper functions?

I have many functions that I create or copy from the Internet.

I wonder if it's worth storing them in a file, which I just include in the script, or should store each function as a static method in the class.

eg. I have a getCurrentFolder () and isFilePhp () function.

if they will be stored in a file in the form in which they are, or in each class:

Folder :: getCurrent () File :: isPhp ();

how do you do it

I know this is a โ€œwhatever you wantโ€ question, but it would be great with some tips / best practices.

thanks.

+6
oop php code-organization organization
source share
1 answer

You are right, this is a very subjective matter, but I would probably use a combination of your two options.

You have a class (say helper) that has __call() (and / or __callStatic() , if you use PHP 5.3+) magic methods , when an undefined method [static] is called, it loads the corresponding auxiliary file and executes the auxiliary function. Keep in mind that including files reduces performance, but I believe that the advantage you get in terms of organizing files far outweighs the tiny success.

A simple example:

 class helper { function __callStatic($m, $args) { if (is_file('./helpers/' . $m . '.php')) { include_once('./helpers/' . $m . '.php'); return call_user_func_array($m, $args); } } } helper::isFilePhp(/*...*/); // ./helpers/isFilePhp.php helper::getCurrentFolder(/*...*/); // ./helpers/getCurrentFolder.php 

You can also optimize this fragment and even have several types of helpers (folder, file), etc. by adding the __call[Static]() magic method to each of your classes and implementing some logic in the structure of the folder / file of your auxiliary files / functions.

+3
source share

All Articles