提高 PHP 代码质量的 36 计(下)
18. 將工具函数封装到类中
假如你在某文件中定义了很多工具函数:
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内建有同名的函数, 这样可以避免冲突.
另一种看法是, 你可以在同个应用中为同个类维护多个版本, 而不导致冲突. 这是封装的基本好处, 无它.
19. Bunch of silly tips
>>使用echo取代print
>>使用str_replace取代preg_replace, 除非你绝对需要
>>不要使用 short tag
>>简单字符串用单引号取代双引号
>>head重定向后记得使用exit
>>不要在循环中调用函数
>>isset比strlen快
>>始中如一的格式化代码
>>不要删除循环或者if-else的括号
不要这样写代码:
if($a == true) $a_count++;
这绝对WASTE.
写成:
if($a == true)
{
$a_count++;
}
不要尝试省略一些语法来缩短代码. 而是让你的逻辑简短.
>>使用有高亮语法显示的文本编辑器. 高亮语法能让你减少错误.
20. 使用array_map快速处理数组
比如说你想 trim 数组中的所有元素. 新手可能会:
foreach($arr as $c => $v)
{
$arr[$c] = trim($v);
}
但使用 array_map 更简单:
$arr = array_map('trim' , $arr);
这会为$arr数组的每个元素都申请调用trim. 另一个类似的函数是 array_walk. 请查阅文档学习更多技巧.
21. 使用 php filter 验证数据
你肯定曾使用过正则表达式验证 email , ip地址等. 是的,每个人都这么使用. 现在, 我们想做不同的尝试, 称为filter.
php的filter扩展提供了简单的方式验证和检查输入.
22. 强制类型检查
$amount = intval( $_GET['amount'] );
$rate = (int) $_GET['rate'];
这是个好习惯.
23. 如果需要,使用profiler如xdebug
如果你使用php开发大型的应用, php承担了很多运算量, 速度会是一个很重要的指标. 使用profile帮助优化代码. 可使用
xdebug和webgrid.
24. 小心处理大数组
对于大的数组和字符串, 必须小心处理. 常见错误是发生数组拷贝导致内存溢出,抛出Fatal Error of Memory size 信息:
$db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB
$cc = $db_records_in_array_format; //2MB more
some_function($cc); //Another 2MB ?
当导入或导出csv文件时, 常常会这么做.
不要认为上面的代码会经常因内存限制导致脚本崩溃. 对于小的变量是没问题的, 但处理大数组的时候就必须避免.
确保通过引用传递, 或存储在类变量中:
$a = get_large_array();
pass_to_function(&$a);
这么做后, 向函数传递变量引用(而不是拷贝数组). 查看文档.
class A
{
function first()
{
$this->a = get_large_array();
$this->pass_to_function();
}
function pass_to_function()
{
//process $this->a
}
}
尽快的 unset 它们, 让内存得以释放,减轻脚本负担.
25. 由始至终使用单一数据库连接
确保你的脚本由始至终都使用单一的数据库连接. 在开始处正确的打开连接, 使用它直到结束, 最后关闭它. 不要像下面这样在函数中打开连接:
function add_to_cart()
{
$db = new Database();
$db->query("INSERT INTO cart .....");
}
function empty_cart()
{
$db = new Database();
$db->query("DELETE FROM cart .....");
}
使用多个连接是个糟糕的, 它们会拖慢应用, 因为创建连接需要时间和占用内存.
特定情况使用单例模式, 如数据库连接.
26. 避免直接写SQL, 抽象之
不厌其烦的写了太多如下的语句:
$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";
$db->query($query); //call to mysqli_query()
这不是个建壮的方案. 它有些缺点:
>>每次都手动转义值
>>验证查询是否正确
>>查询的错误会花很长时间识别(除非每次都用if-else检查)
>>很难维护复杂的查询
因此使用函数封装:
function insert_record($table_name , $data)
{
foreach($data as $key => $value)
{
//mysqli_real_escape_string
$data[$key] = $db->mres($value);
}
$fields = implode(',' , array_keys($data));
$values = "'" . implode("','" , array_values($data)) . "'";
//Final query
$query = "INSERT INTO {$table}($fields) VALUES($values)";
return $db->query($query);
}
$data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);
insert_record('users' , $data);
看到了吗? 这样会更易读和扩展. record_data 函数小心的处理了转义.
最大的优点是数据被预处理为一个数组, 任何语法错误都会被捕获.
该函数应该定义在某个database类中, 你可以像 $db->insert_record这样调用.
查看本文, 看看怎样让你处理数据库更容易.
类似的也可以编写update,select,delete方法. 试试吧.
27. 將数据库生成的内容缓存到静态文件中
如果所有的内容都是从数据库获取的, 它们应该被缓存. 一旦生成了, 就將它们保存在临时文件中. 下次请求该页面时, 可直接从缓存中取, 不用再查数据库.
好处:
>>节约php处理页面的时间, 执行更快
>>更少的数据库查询意味着更少的mysql连接开销
28. 在数据库中保存session
基于文件的session策略会有很多限制. 使用基于文件的session不能扩展到集群中, 因为session保存在单个服务器中. 但数据库可被多个服务器访问, 这样就可以解决问题.
在数据库中保存session数据, 还有更多好处:
>>处理username重复登录问题. 同个username不能在两个地方同时登录.
>>能更准备的查询在线用户状态.
29. 避免使用全局变量
>>使用 defines/constants
>>使用函数获取值
>>使用类并通过$this访问
30. 在head中使用base标签
没听说过? 请看下面:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.
