PHP中微小代码重用的最佳实践

PHP中微小代码重用的最佳实践,php,oop,coding-style,Php,Oop,Coding Style,很长一段时间以来,我都有一个问题——我应该重用代码的一小部分吗?如果是的话,我应该怎么做才能成为最佳实践 关于小代码,我的意思是,例如: if (!is_array($table)) { $table = array($table); } 或 $x=explode(“\n”,$file\u content); $lines=array(); 对于($i=0,$c=count($x);$i如果您的代码主要涉及类和对象,请使用。因为traits的概念专门关注代码重用能力。如前所述,tr

很长一段时间以来,我都有一个问题——我应该重用代码的一小部分吗?如果是的话,我应该怎么做才能成为最佳实践

关于小代码,我的意思是,例如:

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

$x=explode(“\n”,$file\u content);
$lines=array();

对于($i=0,$c=count($x);$i如果您的代码主要涉及类和对象,请使用。因为traits的概念专门关注代码重用能力。

如前所述,traits是一件好事。但过一段时间后可能会有点难以管理,而且它可能不会在所有地方都得到支持,因为它是新的

我要做的是创建具有许多小静态函数的工具类,如:

class ArrayTools
{

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

        return $array;
    }    

}
因此,您可以使用
ArrayTools::CheckArray($array)

调用它,我认为“最佳方式”取决于许多因素,包括您的应用程序使用的技术(过程、OOP),它们运行的PHP版本,等等。例如,traits很有趣也很有用,但它们仅在PHP 5.4.0之后才可用,因此使用此工具对代码片段进行分组,您将无法在运行早期PHP版本的系统中重用它们。另一方面,如果您的应用程序使用OOP样式,并且您组织了可恢复的小代码片段在函数中,它们的使用在OOP应用程序中可能会显得笨拙,并且与特定类中的函数名冲突。在这种情况下,我认为将函数分组在类中似乎更自然


综上所述,类似乎提供了更好的工具,可以按照上面的概述对可恢复的代码片段进行分组,即与早期PHP版本的向后兼容性,避免函数名冲突,等等。)我个人的代码主要是OOP,因此,我有一个Util类,在这个类中,我对表示可恢复的代码段的小函数进行分组,这些代码段彼此不直接相关,因此无法在其他类中进行逻辑分组。

以下是我在普通PHP项目中实际使用的代码段,这些代码片段来自各种框架、良好特性和最佳实践

一,。 下面的代码用于检查您工作的环境,根据环境可以设置一些全局变量、错误报告等

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.');
    }
}
二,

四,

五,

八,

九,


希望这对你有帮助。干杯

traits仅在PHP5.4.0之后才可用。在该语言的早期版本中,您必须使用不同的工具,例如函数或类。@akhilless,对,在这种情况下,OP必须使用解决方案1。Hmmm最好避免静态:)@ShankarDamodaran这是一个容易滑倒的斜坡,但对于这些特定的东西,结合一些代码标准,很容易将它们用作PHP内置函数。但我同意你的观点,危险的东西:)好吧,你是如何在你的应用程序中使用这些类的?您是否创建了这些类的多个对象,或者创建了一个并将其传递给构造函数,或者像@Cleric所示的那样在类中创建静态方法?@MarcinNabiałek您当然可以使用静态方法。另一种可能性是编写一个singleton类,使应用程序中不会充斥完全相同的无限对象。这是我大多数时候喜欢的方法。如果我在应用程序中有几个这样的类,我通常将它们存储在一个singleton注册表类中,该类充当某种身份映射,确保每个对象只加载一次。好的,我理解。我也使用过注册表,但只是用于存储配置/路由/数据库等on@MarcinNabia是的,我也存储数据库访问类和配置类。我想知道这是否只是一个巧合)为数据库连接资源使用全局变量
$link
是一种良好的做法?从什么时候开始?它在普通PHP中,而不是oops PHP项目中。即使我已经提到了这一点,请检查我的上述描述。如果你认为我的方法是错误的。请让我知道您在普通PHP项目中是如何做到这一点的。如果有人在任何地方覆盖
$link
,所有依赖于全局插入的函数都将中断。您的描述说,这些代码片段来自各种框架、良好特性和最佳实践。我的评论只停留在两个字上:最佳实践。你的评论并没有回答我的问题;)是的,我完全同意你的看法,如果有人覆盖了$link,那么它可能不会按它必须的方式运行。在普通PHP中,您没有任何其他方法可以在包含连接的文件中提供连接,如果您知道任何更好的方法,请让我知道,即使我将升级我的代码。如果您不这样做,那么我们可能会复制代码,因此我提出了这种选择。
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.');
    }
}
/* 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>';
    }
}
/* 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)));
}
/* 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;
}
/* 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;
}
/* 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>';
}
/* 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();
    }
}
/* 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');
    }
}
/* 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;
}