php开发那点事儿(二)

十一、不要在你的应用程序中gzip输出,让apache来做

考虑使用ob_gzhandler?不,别这样做。它没有任何意义。PHP应该是来写应用程序的。不要担心PHP中有关如何优化在服务器和浏览器之间传输的数据。

使用apache mod_gzip/mod_deflate通过.htaccess文件压缩内容

十二、从php echo javascript代码时使用json_encode

有些时候一些JavaScript代码是从php动态生成的。


$images = array(

 'myself.png' , 'friends.png' , 'colleagues.png'

);

$js_code = '';

foreach($images as $image)

{

$js_code .= "'$image' ,";

}

$js_code = 'var images = [' . $js_code . ']; ';

echo $js_code;

//Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];


放聪明点。使用json_encode:


$images = array(

 'myself.png' , 'friends.png' , 'colleagues.png'

);

$js_code = 'var images = ' . json_encode($images);

echo $js_code;

//Output is : var images = ["myself.png","friends.png","colleagues.png"]


这不是很整洁?

十三、在写入任何文件之前检查目录是否可写

$contents = "All the content";

$file_path = "/var/www/project/content.txt";

file_put_contents($file_path , $contents);


这完全正确。但有一些间接的问题。file_put_contents可能会因为一些原因而失败:

  • 父目录不存在

  • 目录存在,但不可写

  • 锁定文件用于写入?

因此,在写入文件之前最好能够一切都弄明确。


$contents = "All the content";

$dir = '/var/www/project';

$file_path = $dir . "/content.txt";

if(is_writable($dir))

{

    file_put_contents($file_path , $contents);

}

else

{

    die("Directory $dir is not writable, or does not exist. Please check");

}


通过这样做,你就能得到哪里文件写入失败以及为什么失败的准确信息。

十四、改变应用程序创建的文件的权限

当在Linux环境下工作时,权限处理会浪费你很多时间。因此,只要你的php应用程序创建了一些文件,那就应该修改它们的权限以确保它们在外面“平易近 人”。否则,例如,文件是由“php”用户创建的,而你作为一个不同的用户,系统就不会让你访问或打开文件,然后你必须努力获得root权限,更改文件权 限等等。


// Read and write for owner, read for everybody else

chmod("/somedir/somefile", 0644);

 

// Everything for owner, read and execute for others

chmod("/somedir/somefile", 0755);

十五、不要检查提交按钮值来检查表单提交

if($_POST['submit'] == 'Save')
{
    //Save the things
}


以上代码在大多数时候是正确的,除了应用程序使用多语言的情况。然后“Save”可以是很多不同的东西。那么你该如何再做比较?所以不能依靠提交按钮的值。相反,使用这个:


if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )

{

    //Save the things

}


现在你就可以摆脱提交按钮的值了。

十六、在函数中总是有相同值的地方使用静态变量

//Delay for some time
function delay()
{
    $sync_delay = get_option('sync_delay');

    echo "<br />Delaying for $sync_delay seconds...";
    sleep($sync_delay);
    echo "Done <br />";
}


相反,使用静态变量:


//Delay for some time

function delay()

{

    static $sync_delay = null;

    if($sync_delay == null)

    {

    $sync_delay = get_option('sync_delay');

    }

    echo "<br />Delaying for $sync_delay seconds...";

    sleep($sync_delay);

    echo "Done <br />";

}

十七、不要直接使用$ _SESSION变量

一些简单的例子是:


$_SESSION['username'] = $username;

$username = $_SESSION['username'];


但是这有一个问题。如果你正在相同域中运行多个应用程序,会话变量会发生冲突。2个不同的应用程序在会话变量中可能会设置相同的键名。举个例子,一个相同域的前端门户和后台管理应用程序。因此,用包装函数使用应用程序特定键:


define('APP_ID' , 'abc_corp_ecommerce');

//Function to get a session variable

function session_get($key)

{

    $k = APP_ID . '.' . $key;

    if(isset($_SESSION[$k]))

    {

        return $_SESSION[$k];

    }

    return false;

}

//Function set the session variable

function session_set($key , $value)

{

    $k = APP_ID . '.' . $key;

    $_SESSION[$k] = $value;

    return true;

}

十八、封装实用辅助函数到一个类中

所以,你必须在一个文件中有很多实用函数:


function utility_a()

{

    //This function does a utility thing like string processing

}

function utility_b()

{

    //This function does nother utility thing like database processing

}

function utility_c()

{

    //This function is ...

}


自由地在应用程序中使用函数。那么你或许想要将它们包装成一个类作为静态函数:


class Utility

{

    public static function utility_a()

    {

    }

    public static function utility_b()

    {

    }

    public static function utility_c()

    {

    }

}

//and call them as

$a = Utility::utility_a();

$b = Utility::utility_b();


这里你可以得到的一个明显好处是,如果php有相似名称的内置函数,那么名称不会发生冲突。

从另一个角度看,你可以在相同的应用程序中保持多个版本的相同类,而不会发生任何冲突。因为它被封装了,就是这样。

十九、一些傻瓜式技巧

  • 使用echo代替print

  • 使用str_replace代替preg_replace,除非你确定需要它

  • 不要使用short tags

  • 对于简单的字符串使用单引号代替双引号

  • 在header重定向之后要记得做一个exit

  • 千万不要把函数调用放到for循环控制行中。

  • isset比strlen快

  • 正确和一致地格式化你的代码

  • 不要丢失循环或if-else块的括号。

不要写这样的代码:


if($a == true) $a_count++;


这绝对是一种浪费。

这样写


if($a == true)

{

    $a_count++;

}


不要通过吃掉语法缩短你的代码。而是要让你的逻辑更简短。

使用具有代码高亮功能的文本编辑器。代码高亮有助于减少错误。

二十、使用array_map快速处理数组

比方说,你要trim一个数组的所有元素。新手会这样做:


foreach($arr as $c => $v)

{

    $arr[$c] = trim($v);

}


但它可以使用array_map变得更整洁:


$arr = array_map('trim' , $arr);


这适用于trim数组$arr的所有元素。另一个类似的函数是array_walk。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值