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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With