搜索
首页后端开发php教程提高PHP代码质量的方法

提高PHP代码质量的方法

Mar 08, 2018 pm 02:27 PM
php方法质量

作为一名php程序员当然希望自己的PHP代码质量很高,本文主要和大家分享提高PHP代码质量的方法,希望能帮助到大家。

1.不要使用相对路径

常常会看到:

require_once('../../lib/some_class.php');

该方法有很多缺点:

它首先查找指定的php包含路径, 然后查找当前目录.

因此会检查过多路径.

如果该脚本被另一目录的脚本包含, 它的基本目录变成了另一脚本所在的目录.

另一问题, 当定时任务运行该脚本, 它的上级目录可能就不是工作目录了.

因此最佳选择是使用绝对路径:

define('ROOT' , '/var/www/project/');require_once(ROOT . '../../lib/some_class.php');//rest of the code

 我们定义了一个绝对路径, 值被写死了. 我们还可以改进它. 路径 /var/www/project 也可能会改变, 那么我们每次都要改变它吗? 不是的, 我们可以使用__FILE__常量, 如:

//suppose your script is /var/www/project/index.php//Then __FILE__ will always have that full path.define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));require_once(ROOT . '../../lib/some_class.php');//rest of the code

现在, 无论你移到哪个目录, 如移到一个外网的服务器上, 代码无须更改便可正确运行.

2. 不要直接使用 require, include, include_once, required_once

可以在脚本头部引入多个文件, 像类库, 工具文件和助手函数等, 如:

require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php');

这种用法相当原始. 应该更灵活点. 应编写个助手函数包含文件. 例如:

function load_class($class_name){    //path to the class file
    $path = ROOT . '/lib/' . $class_name . '.php');    require_once( $path );
}

load_class('Database');
load_class('Mail');

有什么不一样吗? 该代码更具可读性.

將来你可以按需扩展该函数, 如:

function load_class($class_name){    //path to the class file
    $path = ROOT . '/lib/' . $class_name . '.php');    if(file_exists($path))
    {        require_once( $path );
    }
}

还可做得更多:

为同样文件查找多个目录

能很容易的改变放置类文件的目录, 无须在代码各处一一修改

可使用类似的函数加载文件, 如html内容.

3. 为应用保留调试代码

在开发环境中, 我们打印数据库查询语句, 转存有问题的变量值, 而一旦问题解决, 我们注释或删除它们. 然而更好的做法是保留调试代码.

在开发环境中, 你可以:

define('ENVIRONMENT' , 'development');if(! $db->query( $query )
{    if(ENVIRONMENT == 'development')
    {        echo "$query failed";
    }    else
    {        echo "Database error. Please contact administrator";
    }
}

在服务器中, 你可以:

define('ENVIRONMENT' , 'production');if(! $db->query( $query )
{    if(ENVIRONMENT == 'development')
    {        echo "$query failed";
    }    else
    {        echo "Database error. Please contact administrator";
    }
}

4. 使用可跨平台的函数执行命令

system, exec, passthru, shell_exec 这4个函数可用于执行系统命令. 每个的行为都有细微差别. 问题在于, 当在共享主机中, 某些函数可能被选择性的禁用. 大多数新手趋于每次首先检查哪个函数可用, 然而再使用它.

更好的方案是封成函数一个可跨平台的函数. 

/**
	Method to execute a command in the terminal
	Uses :	1. system
	2. passthru	3. exec
	4. shell_exec

*/
function terminal($command)
{
	//system
	if(function_exists('system'))
	{
		ob_start();
		system($command , $return_var);
		$output = ob_get_contents();
		ob_end_clean();
	}
	//passthru
	else if(function_exists('passthru'))
	{
		ob_start();
		passthru($command , $return_var);
		$output = ob_get_contents();
		ob_end_clean();
	}

	//exec
	else if(function_exists('exec'))
	{
		exec($command , $output , $return_var);
		$output = implode("\n" , $output);
	}

	//shell_exec
	else if(function_exists('shell_exec'))
	{
		$output = shell_exec($command) ;
	}

	else
	{
		$output = 'Command execution not possible on this system';
		$return_var = 1;
	}

	return array('output' => $output , 'status' => $return_var);
}

terminal('ls');

上面的函数將运行shell命令, 只要有一个系统函数可用, 这保持了代码的一致性. 

5. 灵活编写函数

function add_to_cart($item_id , $qty){
    $_SESSION['cart']['item_id'] = $qty;
}

add_to_cart( 'IPHONE3' , 2 );

使用上面的函数添加单个项目. 而当添加项列表的时候,你要创建另一个函数吗? 不用, 只要稍加留意不同类型的参数, 就会更灵活. 如:

function add_to_cart($item_id , $qty){    if(!is_array($item_id))
    {
        $_SESSION['cart']['item_id'] = $qty;
    }    else
    {        foreach($item_id as $i_id => $qty)
        {
            $_SESSION['cart']['i_id'] = $qty;
        }
    }
}

add_to_cart( 'IPHONE3' , 2 );
add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );

现在, 同个函数可以处理不同类型的输入参数了. 可以参照上面的例子重构你的多处代码, 使其更智能.

6. 有意忽略php关闭标签

我很想知道为什么这么多关于php建议的博客文章都没提到这点.

<?phpecho "Hello";//Now dont close this tag

这將节约你很多时间. 我们举个例子:

一个 super_class.php 文件

<?phpclass super_class{    function super_function()
    {        //super code
    }
}?>//super extra character after the closing tag

index.php

require_once(&#39;super_class.php&#39;);//echo an image or pdf , or set the cookies or session data

这样, 你將会得到一个 Headers already send error. 为什么? 因为 “super extra character” 已经被输出了. 现在你得开始调试啦. 这会花费大量时间寻找 super extra 的位置.

因此, 养成省略关闭符的习惯:

<?phpclass super_class{    function super_function()
    {        //super code
    }
}//No closing tag

这会更好。

7. 在某地方收集所有输入, 一次输出给浏览器

这称为输出缓冲, 假如说你已在不同的函数输出内容:

function print_header(){    echo "<p id=&#39;header&#39;>Site Log and Login links</p>";
}function print_footer(){    echo "<p id=&#39;footer&#39;>Site was made by me</p>";
}

print_header();for($i = 0 ; $i < 100; $i++)
{    echo "I is : $i <br />&#39;;
}
print_footer();

替代方案, 在某地方集中收集输出. 你可以存储在函数的局部变量中, 也可以使用ob_start和ob_end_clean. 如下:

function print_header(){
    $o = "<p id=&#39;header&#39;>Site Log and Login links</p>";    return $o;
}function print_footer(){
    $o = "<p id=&#39;footer&#39;>Site was made by me</p>";    return $o;
}echo print_header();for($i = 0 ; $i < 100; $i++)
{    echo "I is : $i <br />&#39;;
}
echo print_footer();

为什么需要输出缓冲:

>>可以在发送给浏览器前更改输出. 如 str_replaces 函数或可能是 preg_replaces 或添加些监控/调试的html内容.

>>输出给浏览器的同时又做php的处理很糟糕. 你应该看到过有些站点的侧边栏或中间出现错误信息. 知道为什么会发生吗? 因为处理和输出混合了.

8. 发送正确的mime类型头信息, 如果输出非html内容的话.

输出一些xml.

$xml = &#39;<?xml version="1.0" encoding="utf-8" standalone="yes"?>&#39;;
$xml = "<response>
  <code>0</code>
</response>";//Send xml dataecho $xml;

工作得不错. 但需要一些改进.

$xml = &#39;<?xml version="1.0" encoding="utf-8" standalone="yes"?>&#39;;
$xml = "<response>
  <code>0</code>
</response>";//Send xml dataheader("content-type: text/xml");echo $xml;

注意header行. 该行告知浏览器发送的是xml类型的内容. 所以浏览器能正确的处理. 很多的javascript库也依赖头信息.

类似的有 javascript , css, jpg image, png image:

JavaScript

header("content-type: application/x-javascript");
echo "var a = 10";

CSS

header("content-type: text/css");echo "#p id { background:#000; }";

曾经遇到过在mysql表中设置了unicode/utf-8编码,  phpadmin也能正确显示, 但当你获取内容并在页面输出的时候,会出现乱码. 这里的问题出在mysql连接的字符编码.

//Attempt to connect to database$c = mysqli_connect($this->host , $this->username, $this->password);//Check connection validityif (!$c) 
{	die ("Could not connect to the database host: <br />". mysqli_connect_error());
}//Set the character set of the connectionif(!mysqli_set_charset ( $c , &#39;UTF8&#39; ))
{	die(&#39;mysqli_set_charset() failed&#39;);
}

一旦连接数据库, 最好设置连接的 characterset. 你的应用如果要支持多语言, 这么做是必须的.

10. 使用 htmlentities 设置正确的编码选项

php5.4前, 字符的默认编码是ISO-8859-1, 不能直接输出如À â等.

$value = htmlentities($this->value , ENT_QUOTES , CHARSET);

php5.4以后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍然要留意编码问题,.

以上是提高PHP代码质量的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
优化PHP代码:减少内存使用和执行时间优化PHP代码:减少内存使用和执行时间May 10, 2025 am 12:04 AM

TOOPTIMIZEPHPCODEFORDUSEMEMORYUSAGEAGEAGEAGEAGEAGEANDEXECUTITIEM,关注台词:1)USEREEREFERESCENCENCINCOPYINSTEADOFCOPYINGINATATASTRUCTURESTROUCTURESTOREDUCEMORYCONSUMPTION.2)杠杆phphppphpphp'sbuilt intimpunctionslikearray_mapforfunctionslikearray_mapforfforfforfforfasterapasterexecution.3)

PHP电子邮件:分步发送指南PHP电子邮件:分步发送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自动化notifications andMarketingCampaigns.1)设置设置yourphpenvironcormentswironmentswithaweberswithawebserverserverserverandphp,确保themailfunctionisenabled.2)useabasicscruct

如何通过PHP发送电子邮件:示例和代码如何通过PHP发送电子邮件:示例和代码May 09, 2025 am 12:13 AM

发送电子邮件的最佳方法是使用PHPMailer库。1)使用mail()函数简单但不可靠,可能导致邮件进入垃圾邮件或无法送达。2)PHPMailer提供更好的控制和可靠性,支持HTML邮件、附件和SMTP认证。3)确保正确配置SMTP设置并使用加密(如STARTTLS或SSL/TLS)以增强安全性。4)对于大量邮件,考虑使用邮件队列系统来优化性能。

高级PHP电子邮件:自定义标题和功能高级PHP电子邮件:自定义标题和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP发送电子邮件的指南使用PHP和SMTP发送电子邮件的指南May 09, 2025 am 12:06 AM

使用PHP和SMTP发送邮件可以通过PHPMailer库实现。1)安装并配置PHPMailer,2)设置SMTP服务器细节,3)定义邮件内容,4)发送邮件并处理错误。使用此方法可以确保邮件的可靠性和安全性。

使用PHP发送电子邮件的最佳方法是什么?使用PHP发送电子邮件的最佳方法是什么?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依赖注入的最佳实践PHP中依赖注入的最佳实践May 08, 2025 am 12:21 AM

使用依赖注入(DI)的原因是它促进了代码的松耦合、可测试性和可维护性。1)使用构造函数注入依赖,2)避免使用服务定位器,3)利用依赖注入容器管理依赖,4)通过注入依赖提高测试性,5)避免过度注入依赖,6)考虑DI对性能的影响。

PHP性能调整技巧和技巧PHP性能调整技巧和技巧May 08, 2025 am 12:20 AM

phperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovesponsemetimes.2)优化

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。