search
HomeBackend DevelopmentPHP Tutorial提高 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标签


没听说过? 请看下面:


提高 PHP 代码质量的 36 计(下)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version