Home php教程 php手册 《Advanced PHP Programming》读书笔记

《Advanced PHP Programming》读书笔记

Jun 06, 2016 pm 07:54 PM
notes read

此书无中文版,但是写的极好!本来想翻译的,可是时间不允许了。 http://www.amazon.com/Advanced-PHP-Programming-George-Schlossnagle/dp/0672325616/ref=pd_rhf_dp_p_t_1 约定:加粗字体表示章节,由于时间关系解释性的说明全部省略。 《高级PHP程序设计

此书无中文版,但是写的极好!本来想翻译的,可是时间不允许了。

http://www.amazon.com/Advanced-PHP-Programming-George-Schlossnagle/dp/0672325616/ref=pd_rhf_dp_p_t_1

 

约定:加粗字体表示章节,由于时间关系解释性的说明全部省略。

《高级 PHP程序设计》

简介

PHP在企业级开发

 一个编程语言满足下面6方面才能满足关键的商业应用:

快速原型设计和实施

现代编程范式的支持

可伸缩性

高性能

互操作性

可扩展性

平台和版本

本书主要是针对php5,更主要是使你的代码更快,更敏捷,设计的更好。

本书基于linux编写的。
平台和版本
平台和版本


第一部分 实施和开发方法
第一章 代码风格

选择适合你的代码风格

代码格式化和布局

包括行的长度,使用空白,使用SQL是最基本的技能。

 

缩进

本书使用缩进来表示代码块,但不能夸大其重要性。虽然php中不强制缩进,但是缩进是一个有用的工具。

考虑下面的代码
if($month  == 'september' || $month  == 'april' || $month  == 'june' || $month  ==
'november') { return 30;
}
else if($month == 'february') {
if((($year % 4 == 0) && !($year % 100)) || ($year % 400 == 0)) {
return 29;
}
else {
return 28;
}
}
else {
return 31;
}


和下面的代码比较,除了缩进都是相同的。

if($month  == 'september' ||
   $month  == 'april'     ||
   $month  == 'june'      ||
   $month  == 'november') {
  return 30;
}
else if($month == 'february') {
  if((($year % 4 == 0) && ($year % 100)) || ($year % 400 == 0)) {
    return 29;
  }
  else {
    return 28;
  }
}
else {
  return 31;
}
Copy after login


后一段代码比前一段在逻辑上更好分辨。

 

当你使用tab代码缩进,你需要做出一致性选择使用硬或软tab,硬是常规选项,而软实际上是由一定量的空格表示,使用软的好处是他们总是相同,我比较喜欢软。当你使用硬,在多个开发人员使用不同的编辑器会造出不一致。

 

 

行长

前面的第一段代码太长,这样不便于跟踪和调试,应该把长行分为多行,例如:

<strong>if($month  == 'september' || $month  == 'april' ||
   $month  == 'june' || $month  == 'november') {
        return 30;
}
</strong>
Copy after login


可以缩进对齐条件

<strong>if($month  == 'september' ||
   $month  == 'april' ||
   $month  == 'june' ||
   $month  == 'november')
{
  return 30;
}
</strong>
Copy after login


这个方法同样适合于函数的参数

mail("postmaster@example.foo",
     "My Subject",
     $message_body,
     "From: George Schlossnagle george@omniti.com>\r\n");

一般,我会80个字符就要换行,因为这是一个标准unix终端窗口的宽度。

 

使用空白

$lt = localtime();
$name = $_GET['name'];
$email = $_GET['email'];
$month = $lt['tm_mon'] + 1;
$year = $lt['tm_year'] + 1900;
$day = $lt['tm_day'];
$address = $_GET['address'];
Copy after login

 

通过空白进行逻辑分组

$name    = $_GET['name'];
$email   = $_GET['email'];
$address = $_GET['address'];

$lt    = localtime();
$day   = $lt['tm_day'];
$month = $lt['tm_mon'] + 1;
$year  = $lt['tm_year'] + 1900;
Copy after login


SQL指引

$query = "SELECT FirstName, LastName FROM employees, departments WHERE
employees.dept_id = department.dept_id AND department.Name = 'Engineering'";
Copy after login

 

上面的sql组织的不好,可以从以下方面修改:

关键字大写;关键字换行;使用表的别名保持代码整洁

$query = "SELECT firstname,
                 lastname
          FROM employees e,
              departments d
          WHERE e.dept_id = d.dept_id
          AND d.name = 'Engineering'";
Copy after login


控制流结构

两种方式:条件和循环

 

控制结构使用大括号

php采用c语言风格,单行php条件语句不用使用大括号,例如下面的代码是正确的:

if(isset($name))
  print "Hello $name";
Copy after login


但是,这样会引起混乱,应该总是使用大括号

if(isset($name)) {
    print "Hello $name";
}
else {
    print "Hello Stranger";
}

Copy after login


始终使用大括号

条件语句中三种使用括号的风格

BSD风格我比较喜欢

if ($condition)
{
      // statement
}
Copy after login

 

GNU风格

if ($condition)
  {
      // statement
  }

Copy after login

K&R 风格

if ($condition) {
      // statement
}

Copy after login

for和foreach和while
如果for或者foreach循环可以做的事情不应该使用while循环

function is_prime($number)
{
  if(($number % 2) != 0) {
    return true;
  }
  $i = 0;
  while($i <p><br>不小心会增加无限循环,使用for更加自然</p><pre class="brush:php;toolbar:false">function is_prime($number)
{
  if(($number % 2) != 0) {
    return true;
  }
  for($i=3; $i <p>对数组迭代的时候foreach比for更好</p><pre class="brush:php;toolbar:false">$array = (3, 5, 10, 11, 99, 173);
foreach($array as $number) {
  if(is_prime($number)) {
    print "$number is prime.\n";
  }
}

Copy after login

这样比使用for更快,因为避免计数器的使用。


使用break和continue控制循环

不需要循环的时候使用break跳出循环

$has_ended = 0;
while(($line =  fgets($fp)) !== false) {
  if($has_ended) {
  }
  else {
    if(strcmp($line, '_END_') == 0) {
       $has_ended = 1;
    }
    if(strncmp($line, '//', 2) == 0) {

    }
    else {
      // parse statement
    }
  }
}


Copy after login


这个例子比前面的更短,而且避免了深层次的嵌套

while(($line =  fgets($fp)) !== false) {
  if(strcmp($line, '_END_') == 0) {
    break;
  }
  if(strncmp($line, '//', 2) == 0) {
    continue;
  }
  // parse statement
}

Copy after login

避免很深层的循环

常见的错误是在一个浅循环中使用深层嵌套

$fp = fopen("file", "r");
if ($fp) {
  $line = fgets($fp);
  if($line !== false) {
    // process $line
  }  else {
    die("Error: File is empty);
}
else {  die("Error: Couldn't open file");
}

Copy after login


消除不必要的嵌套

$fp = fopen("file", "r");
if (!$fp) {
 die("Couldn't open file");
}
$line = fgets($fp);
if($line === false) {
 die("Error: Couldn't open file");
}
// process $line

Copy after login

命名符号

function test($baz)
{
  for($foo = 0; $foo 下面的代码使用更有意义的变量名和函数名<br><pre class="brush:php;toolbar:false">function create_test_array($size)
{
  for($i = 0; $i <p>三类命名规则:</p><p>全局变量要使用在全局范围</p><p>长时间存在的变量可存在于任何范围但要包含重要信息或大块代码的引用</p><p>临时变量用于小部分代码保持临时信息<br></p><p><strong>常量和真正的全局变量</strong></p><p>全局变量和常量要使用大写字母,便于辨识。</p><pre class="brush:php;toolbar:false">$CACHE_PATH = '/var/cache/';
...
function list_cache()
{
  global $CACHE_PATH;
  $dir = opendir($CACHE_PATH);
  while(($file = readdir($dir)) !== false && is_file($file)) {
    $retval[] = $file;
  }
  closedir($dir);
  return $retval;
}

Copy after login


错误使用全局变量的原因:

它们可以在任何地方被改变不好定位;

污染了全局命名空间,例如使用一个全局变量命名为计数器$counter同时你还有另一个计数器也是$counter,随着代码的增长这种冲突越来越不可避免;

解决方案是使用一个“访问器”函数。

global $database_handle;
global $server;
global $user;
global $password;
$database_handle = mysql_pconnect($server, $user, $password);

Copy after login


可以使用如下的类:

class Mysql_Test {
  public $database_handle;
  private $server = 'localhost';
  private $user = 'test';
  private $password = 'test';
  public function __construct()
  {
    $this->database_handle =
      mysql_pconnect($this->server, $this->user, $this->password);
  }
}

Copy after login

第二章中将探索更有效的方式处理这个例子,当我们处理单例模式和封装类时。

有时候,你需要访问一个特定的变量,像这样:

$US_STATES = array('Alabama', ... , 'Wyoming');

Copy after login


这个例子中类做了太多的事情,如果你想在这里避免全局变量,你可以使用一个访问函数全局数组使用一个静态变量。

function us_states()
{
  static $us_states = array('Alabama', ... , 'Wyoming');
  return $us_states;
}

Copy after login

长时间存在的变量
应该有简洁描述性的名称,长时间存在的变量不一定是全局的,甚至在主题范围内。

下面例子中变量名帮助理解代码的意思。

function clean_cache($expiration_time)
{
  $cachefiles = list_cache();
  foreach($cachefiles as $cachefile) {
    if(filemtime($CACHE_PATH."/".$cachefile) > time() + $expiration_time) {
      unlink($CACHE_PATH."/".$cachefile);
    }
  }
}

Copy after login

临时变量

临时变量的名称要简明扼要。由于临时变量通常只存在于一个小的代码块,所以他们并不需要有说明性名称。 特别是用于循环的数值变量应该始终被命名为J,K,L,M,和n
等。 

比较这个例子

$number_of_parent_indices = count($parent);
for($parent_index=0; $parent_index <p><br>例如</p><pre class="brush:php;toolbar:false">$pcount = count($parent);
for($i = 0; $i <p><br>这样会更妙</p><pre class="brush:php;toolbar:false">foreach($parent as $child) {
  foreach($child as $element) {
    my_function($element);
  }
}

Copy after login


 多词名称

$numElements = count($elements);

$num_elements = count($elements);

推荐第二种命名方法,原因是:

情况发生变化,你为了保持一致性不得不$CACHEDIR和$PROFANITYMACROSET

数据库不区分大小写;

非英语本土人士会在字典中更好的查到。

 

函数名

函数名和正常的变量名类似的处理方式,全部小写,多字要用下划线分割,推荐K&R风格:

function print_hello($name)
{
  print "Hello $name";
}

Copy after login

 foo() 和bar() 反映不出你的代码更多的信息,让你的代码看起来很不专业。

 

类名

参考官方的Java风格指南,类名应遵循以下规则:

一个类的名字第一个字母是大写;
下划线应该用来模拟嵌套的命名空间;

多字的类名应连接在一起,每个单词的首字母应大写。

class XML_RSS {}
class Text_PrettyPrinter {}

Copy after login

方法名

Java风格的串连字多字的方法名称是第一个字母后的单词第一个字母大写

class XML_RSS
{
    function startHandler() {}
}
Copy after login


 命名一致性

类似目的的变量保持类似的名称

$num_elements = count($elements);
...
$objects_cnt = count($objects);

推荐下面的风格
Copy after login
$max_elements;
$min_elements;
$sum_elements;
$prev_item;
$curr_item;
$next_item;
Copy after login
<strong>匹配变量名和架构名</strong>
Copy after login
与数据库中的记录相关联的变量名称应该始终有相匹配的名字。
Copy after login
$query = "SELECT firstname, lastname, employee_id
          FROM employees";
$results = mysql_query($query);
while(list($firstname, $lastname, $employee_id) = mysql_fetch_row($results)) {
  // ...
}

Copy after login
下面的代码容易混淆
Copy after login
$first_query = "SELECT a,b
          FROM subscriptions
          WHERE subscription_id = $subscription_id";
$results = mysql_query($first_query);
list($a, $b) = mysql_fetch_row($results);
// perform necessary logic
$new_a = $b;
$new_b = $a;
$second_query = "UPDATE subscriptions
                 SET a = '$new_a',
                     B = '$new_b'
                 WHERE subscription_id = $subscription_id";
Mysql_query($second_query);

Copy after login

开发人员为了保持列名和变量名在update中一致性

$first_query = "SELECT a,b
          FROM subscriptions
          WHERE subscription_id = $subscription_id";
$results = mysql_query($first_query);
list($b, $a) = mysql_fetch_row($results);
// perform necessary logic
$second_query = "UPDATE subscriptions
                 SET a = '$a',
                     B = '$b'
                 WHERE subscription_id = $subscription_id";
mysql_query($second_query);

Copy after login

这一代码会完全混乱不堪。

 

避免代码混乱

一致的代码风格让代码看一起是清晰的

print "Hello $username";
?>

但是不应该使用!
Copy after login

因为无法打印正常的XML内联文件

<?xml version="1.0" ?>
Copy after login


<?php print "Hello $username";
? >

Copy after login


 

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to delete Xiaohongshu notes How to delete Xiaohongshu notes Mar 21, 2024 pm 08:12 PM

How to delete Xiaohongshu notes? Notes can be edited in the Xiaohongshu APP. Most users don’t know how to delete Xiaohongshu notes. Next, the editor brings users pictures and texts on how to delete Xiaohongshu notes. Tutorial, interested users come and take a look! Xiaohongshu usage tutorial How to delete Xiaohongshu notes 1. First open the Xiaohongshu APP and enter the main page, select [Me] in the lower right corner to enter the special area; 2. Then in the My area, click on the note page shown in the picture below , select the note you want to delete; 3. Enter the note page, click [three dots] in the upper right corner; 4. Finally, the function bar will expand at the bottom, click [Delete] to complete.

Can deleted notes on Xiaohongshu be recovered? Can deleted notes on Xiaohongshu be recovered? Oct 31, 2023 pm 05:36 PM

Notes deleted from Xiaohongshu cannot be recovered. As a knowledge sharing and shopping platform, Xiaohongshu provides users with the function of recording notes and collecting useful information. According to Xiaohongshu’s official statement, deleted notes cannot be recovered. The Xiaohongshu platform does not provide a dedicated note recovery function. This means that once a note is deleted in Xiaohongshu, whether it is accidentally deleted or for other reasons, it is generally impossible to retrieve the deleted content from the platform. If you encounter special circumstances, you can try to contact Xiaohongshu’s customer service team to see if they can help solve the problem.

What should I do if the notes I posted on Xiaohongshu are missing? What's the reason why the notes it just sent can't be found? What should I do if the notes I posted on Xiaohongshu are missing? What's the reason why the notes it just sent can't be found? Mar 21, 2024 pm 09:30 PM

As a Xiaohongshu user, we have all encountered the situation where published notes suddenly disappeared, which is undoubtedly confusing and worrying. In this case, what should we do? This article will focus on the topic of &quot;What to do if the notes published by Xiaohongshu are missing&quot; and give you a detailed answer. 1. What should I do if the notes published by Xiaohongshu are missing? First, don't panic. If you find that your notes are missing, staying calm is key and don't panic. This may be caused by platform system failure or operational errors. Checking release records is easy. Just open the Xiaohongshu App and click &quot;Me&quot; → &quot;Publish&quot; → &quot;All Publications&quot; to view your own publishing records. Here you can easily find previously published notes. 3.Repost. If found

How to connect Apple Notes on iPhone in the latest iOS 17 system How to connect Apple Notes on iPhone in the latest iOS 17 system Sep 22, 2023 pm 05:01 PM

Link AppleNotes on iPhone using the Add Link feature. Notes: You can only create links between Apple Notes on iPhone if you have iOS17 installed. Open the Notes app on your iPhone. Now, open the note where you want to add the link. You can also choose to create a new note. Click anywhere on the screen. This will show you a menu. Click the arrow on the right to see the "Add link" option. click it. Now you can type the name of the note or the web page URL. Then, click Done in the upper right corner and the added link will appear in the note. If you want to add a link to a word, just double-click the word to select it, select "Add Link" and press

How to add product links in notes in Xiaohongshu Tutorial on adding product links in notes in Xiaohongshu How to add product links in notes in Xiaohongshu Tutorial on adding product links in notes in Xiaohongshu Mar 12, 2024 am 10:40 AM

How to add product links in notes in Xiaohongshu? In the Xiaohongshu app, users can not only browse various contents but also shop, so there is a lot of content about shopping recommendations and good product sharing in this app. If If you are an expert on this app, you can also share some shopping experiences, find merchants for cooperation, add links in notes, etc. Many people are willing to use this app for shopping, because it is not only convenient, but also has many Experts will make some recommendations. You can browse interesting content and see if there are any clothing products that suit you. Let’s take a look at how to add product links to notes! How to add product links to Xiaohongshu Notes Open the app on the desktop of your mobile phone. Click on the app homepage

How to publish notes tutorial on Xiaohongshu? Can it block people by posting notes? How to publish notes tutorial on Xiaohongshu? Can it block people by posting notes? Mar 25, 2024 pm 03:20 PM

As a lifestyle sharing platform, Xiaohongshu covers notes in various fields such as food, travel, and beauty. Many users want to share their notes on Xiaohongshu but don’t know how to do it. In this article, we will detail the process of posting notes on Xiaohongshu and explore how to block specific users on the platform. 1. How to publish notes tutorial on Xiaohongshu? 1. Register and log in: First, you need to download the Xiaohongshu APP on your mobile phone and complete the registration and login. It is very important to complete your personal information in the personal center. By uploading your avatar, filling in your nickname and personal introduction, you can make it easier for other users to understand your information, and also help them pay better attention to your notes. 3. Select the publishing channel: At the bottom of the homepage, click the &quot;Send Notes&quot; button and select the channel you want to publish.

Microsoft rolls out reading progress update, reading coach coming in summer 2022 Microsoft rolls out reading progress update, reading coach coming in summer 2022 Apr 27, 2023 pm 08:19 PM

The education landscape has changed dramatically since the pandemic began. This affects both teachers and students, and even their educational needs. As a result, we have witnessed the birth of various innovative educational tools, including reading progress. Now, Microsoft plans to take learning to the next level by introducing reading coaches. "We're excited to share that reading coaching will be built into Immersive Reader, our free reading tool that supports equitable education," Microsoft Vice President of Education Paige Johnson wrote in a Microsoft Education blog post. “Now, students at every level can receive high-quality, personalized reading fluency instruction through the Microsoft 365 app. Embedding reading coaches into Immersive Reader also provides students with Microsoft Translate

Scan printed and handwritten notes in the Notes app for iPhone Scan printed and handwritten notes in the Notes app for iPhone Nov 29, 2023 pm 11:19 PM

In 2022, Apple added a new feature to the Notes app on iPhone and iPad that allows you to quickly scan printed or handwritten text and save it in a digital text format. Read on to learn how it works. On earlier versions of iOS and iPadOS, scanning text into Apple's Notes app required tapping the note's text field and then tapping the "Live Text" option in the pop-up menu. However, Apple is making it easier to digitize real-world notes in 2022. The following steps show you how to do this on a device running iOS 15.4 or iPadOS 15.4 and above. On your iPhone or iPad, open "

See all articles