Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

As mentioned already traits are a good thing. But might be a bit hard to manage after a while, and it might not be supported everywhere since its new.

What I do is to create Tool classes that have a lot small static functions, like:

class ArrayTools
{

    static public function CheckArray($array)
    {
        if (!is_array($array))
        {
            $array = array($array);  
        }

        return $array;
    }    

}

So you can call it with ArrayTools::CheckArray($array)

Please go with traits if your code mainly involves classes and objects.. As the the concept of traits exclusively focusses on code reuse ability.

Following are the code snippets which actually I use with Plain PHP projects, these code snippets are used from various frameworks good traits and best practices.

1. The following code is used to check the environment in which your working, based on the environment you can set the some global variables, error reporting as so on.

if(!defined('ENVIRONMENT')){
    define('ENVIRONMENT','DEVELOPMENT');
}

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'DEVELOPMENT':
        case 'TESTING':
            $base_url   =   'http://localhost/project_name/';
            error_reporting(E_ALL);
            break;

        case 'PRODUCTION':
            $base_url   =   'http://hostname/project_name/';
            error_reporting(0);
            break;

        default:
            exit('The application environment is not set correctly.');
    }
}

2.

/* This function is used to PRINT the ARRAY data in the pre formatted manner */
if (!function_exists('pr')) {
    function pr($data) {
        echo '<pre>', print_r($data), '</pre>';
    }
}

3.

/* This function is used to Sanitize the user data and make data safe to insert into the database */
function sanitize($data) {
    global $link;
    $data = trim($data);
    return htmlentities(strip_tags(mysqli_real_escape_string($link, $data)));
}

4.

/* Used to get the difference of 2 arrays
   Returns the array with difference    
 */
function multi_diff($arr1,$arr2){
  $result = array();
  foreach ($arr1 as $k=>$v){
    if(!isset($arr2[$k])){
      $result[$k] = $v;
    } else {
      if(is_array($v) && is_array($arr2[$k])){
        $diff = multi_diff($v, $arr2[$k]);
        if(!empty($diff))
          $result[$k] = $diff;
      }
    }
  }
  return $result;
}

5.

/* This fnction is used to generate the random keys of specific length
  Accepts parameter of certain length if not specified it will generate 20 bit length automatically
 */
function generate_random_key($length = 20) {
    //Initializing the varialble
    $keystring = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
    $random_key = '';
    for ($i = 0; $i < $length; $i++) {
        $random_key.=$keystring[rand(0, strlen($keystring) - 1)];
    }
    //Return the randomly generated key
    return $random_key;
}

6.

/* This function outputs the errors in ul>li format with unstyled
 * To get the bullets styling remove class='list-unstyled' in <ul> tag */
function output_errors($errors){
    $output =   array();

    foreach ($errors as $error) {
        $output[]   =   '<li>'.$error.'</li>';
    }
    return '<ul class="list-unstyled">'.implode('', $output).'</ul>';
}

7.

/* Checks whether the user is loggedin else will redirect to the protectect page */
function protected_page(){
    if(is_loggedin() === false){
//        header('Location: protected.php');
        header('Location: logout.php');
        exit();
    }
}

8.

/* If user tries to access the page directly accessing through the URL,
 * If already loggedin then redirect him to any of the inner page 
 */
function login_redirect(){
    if(is_loggedin() === true){
        header('Location: home.php');
    }
}

9.

/* This function is used to check whether the user exists or not */
function email_exists($email){
    /* Your Code */
}


/* This function is used to check whether the user isActive or not */
function is_active($email){
    /* Your Code */
}


/* This function will get the userid from the email */
function userid_from_email($email) {
    /* Your Code */
}

/* This fucntion is used to login the user based on the email-id and password */
function login($email,$password){
    /* Your Code */
}

/* Check whether the USER is loggedin or not */
function is_loggedin(){
    return (isset($_SESSION['userid'])) ? true : false;
}

Hope this helps you. Cheers!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top