Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to store helper functions?

i've got a lot of functions i create or copy from the web.

i wonder if i should store them in a file that i just include into the script or should i store each function as a static method in a class.

eg. i've got a getCurrentFolder() and a isFilePhp() function.

should they be stored in a file as they are or each in a class:

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

how do you do?

i know this is kinda a "as u want" question but it would be great with some advices/best practices

thanks.

like image 355
never_had_a_name Avatar asked Apr 27 '10 00:04

never_had_a_name


People also ask

Where do you put helper methods?

If you're looking to write custom helper methods, the correct directory path is app/helpers . You write your helpers inside a helper module. Every Rails application comes with a base helper module by default, it's called ApplicationHelper .

Should helper functions go above or below?

According to Clean Code you should order your methods from top to bottom, in the order they are called. So it reada like a poem.

Where do you put helper functions in Django?

If they are related to a specific app, I usually just put them in the related app folder and name the file, 'functions.py'. If they're not specific to an app, I make a commons app for components (tests, models, functions, etc) that are shared across apps. Save this answer.


1 Answers

You're right, this is highly subjective matter however I would probably use a mix of your two options.

You have a class (say Helper) that has the __call() (and/or __callStatic() if you're using PHP 5.3+) magic methods, when a non defined [static] method is called it'll load the respective helper file and execute the helper function. Keep in mind though that including files decreases performance, but I believe the benefit you gain in terms of file organization far outweighs the tiny performance hit.

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 further optimize this snippet and even have several types of helpers (Folder, File) and so on, by adding a __call[Static]() magic method to each of your classes and implementing some logic in the folder/file structure of your helper files/functions.

like image 147
Alix Axel Avatar answered Oct 03 '22 04:10

Alix Axel