PHP 新手 : How to write good code

标签 php coding-style

<分区>

由于此处许多与 PHP 相关的问题都是非常基础的,因此我建议准备一些提示和技巧。

这可能是一个起点:

  • 检查尽可能多的方法的输入参数(参见 assert() )。
  • 将所有错误记录到一个日志文件中,并使用您的管理后端将其可视化(参见 set_error_handler() )。
  • 尽可能多地使用类型提示(参见 type-hinting)
  • 错误级别设置为绝对最大值。然后以这样的方式编码,不会出现任何警告(参见 error_reporting() )。
  • 了解 PHP 为什么以及如何实现和转换数据类型(参见 type jugglingstring conversions)

那么问题来了:PHP新手应该怎么做呢?

UPDATE-1

由于很多人评论了这个问题,我建议重新打开它。请单击下面的相应链接。

最佳答案

测试

你应该更好地测试你的代码,可能练习 TDD .感谢PHPUnit,你可以做到这一点.牢记Uncle Bob's three rules练习 TDD。

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.
  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

You must begin by writing a unit test for the functionality that you intend to write. But by rule 2, you can't write very much of that unit test. As soon as the unit test code fails to compile, or fails an assertion, you must stop and write production code. But by rule 3 you can only write the production code that makes the test compile or pass, and no more.

If you think about this you will realize that you simply cannot write very much code at all without compiling and executing something. Indeed, this is really the point. In everything we do, whether writing tests, writing production code, or refactoring, we keep the system executing at all times. The time between running tests is on the order of seconds, or minutes. Even 10 minutes is too long.

你应该尝试拥有高code coverage . PHPUnit 也可以做到 code coverage analyses感谢xdebug . Refactoring code那是smelly ( list ) 应该很容易,因为您的测试用例已经存在。

安全

性能

  • 学习和使用APC

Caching the compiled bytecode of PHP scripts to avoid the overhead of parsing and compiling source code on each request (some or all of which may never even be executed). To further improve performance, the cached code is stored in shared memory and directly executed from there, minimizing the amount of slow disk reads and memory copying at runtime.

The famous quotation, "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil", by Donald Knuth,6 has also been mistakenly attributed to Hoare (by Knuth himself), although Hoare disclaims authorship.

关于PHP 新手 : How to write good code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6685829/

相关文章:

Nginx 或 PHP FPM 忽略 php.ini 中的 memory_limit

javascript - 根据 ajax 请求响应做出决定时遇到问题

c++ - 为什么在 C++ 类中的成员变量上使用前缀

C++:在表达式和函数调用上使用 '.' 运算符

c++ - 是否有良好/广泛采用的 c++ 模板编码约定/标准?

Python 风格 - 小数点后加 0

javascript - 在 PHP 中单击复选框时如何禁用输入?

php - 循环遍历表格行 php CSS

python - 在 Python 中,什么时候应该使用函数而不是方法?

php - 如何将数据传递到 Codeigniter 模板