Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for tiny code reuse in PHP

For a long time I have a problem - should I reuse small parts of code and if so, how should I do it so it would be the best practice.

What I mean about small code is for example:

if (!is_array($table)) {
    $table = array($table);  
}

or

$x = explode("\n", $file_content);

$lines = array();

for ($i=0, $c = count($x); $i<$c; ++$i) {
  $x[$i] = trim($x[$i]);
  if ($x[$i] == '') {
     continue;
  }          
  $lines[] = $x[$i];      
}

Such tiny parts of code may be used in many classes in one project but some of them are used also in many projects.

There are many possible solutions I think:

  1. create simple function file and put them all reusable piece of codes as function, include them simple in project and use them whenever I want
  2. create traits for those piece of codes and use them in classes
  3. reuse code by simple copy paste or creating function in specific class (??)
  4. other ?

I think all of those solutions have their pros and cons.

Question: What method should I use (if any) to reuse such code and why is this approach the best one in your opinion?

like image 260
Marcin Nabiałek Avatar asked Aug 24 '26 05:08

Marcin Nabiałek


1 Answers

I think that "the best way" depends on many factors including the technology your applications use (procedural, OOP), versions of PHP they run on, etc. For example, traits are interesting and useful but they are available only since php 5.4.0 so using this tool to group your code snippets you will not be able to reuse them in systems running on earlier PHP versions. On the other hand if your app uses an OOP style and you organized your resuable small code snippets in functions, their usage may seem awkward in an OOP app and conflict with the function names in a particular class. In this case I think grouping your functions in classes would seem more natural.

Putting everything together, it seems that classes provide better tool for grouping resuable code snippets in terms outline above, namely backward compatibility with earlier PHP versions, avoiding function names conflicts, etc.) Personally I code mostly in OOP, so i have a Util class where I group small functions representing resuable pieces of code snippets that do not directly relate to each other and thus could not be logically groupped in other classes.

like image 180
akhilless Avatar answered Aug 25 '26 20:08

akhilless