Modern PHP读书笔记一

关于PHP,你们的误解比较多,但其实现代PHP是一门不管开发效率仍是执行效率都至关高的编程语言。关于现代PHP的各方面特性,你们能够参考<Modern PHP>做者以前写的 PHP the right way,中文翻译:PHP之道。同时,做者也是比较流行的PHP框架 – Slim 的开发者。因此这本书很是值得已读,甚至你只须要懂一些OOP的概念便可,并不须要你懂PHP开发。php

Part 1. Language Feature

Features

Namespaces

PHP命名空间使用 “\” 字符来分割sumnamespaces。与操做系统的物理文件系统不一样,PHP命名空间是一个抽象概念,没必要跟文件目录一一对应。大多数PHP Components都是根据PSR-4 autoloader standard来组织subnamespaces与文件目录的映射关系的。html

从技术上来讲,namespaces仅仅是一个PHP语言的符号,PHP解释器使用这个符号来做为一组classes/interfaces/functions/constants集合的前缀,仅此而已。
Namespaces are important because they let us create sandboxed code that works alongside other developer's code. This is the cornerstone concept of the modern PHP component ecosystem.前端

Helpful Tips

1. Multiple imports
bad:nginx

<?php
use Symfony\Component\HttpFoundation\Request,
        Symfony\Component\HttpFoundation\Response,
        Symfony\Component\HttpFoundation\Cookie;

good:laravel

<?php
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Component\HttpFoundation\Cookie;

2. one class per filegit

3.Global namespace
若是咱们引用一个没有命名空间的class/interface/function/constant,PHP会首先假设这个class/interface/function/constant在当前的命名空间中。若是在当前命名空间中没有找到,PHP才会开始resolve。而对于那些没有没有命名空间的代码,PHP认为他们存在于global namespace。github

PSR-4web

Code to an interface

An interface is a contract between tow PHP objects that lets one object depend not on what another object is but, instead, on what another can do.npm

Trait

A trait is a partial class implementation(i.e., constants, properties, and methods) that can be mixed into one or more existing PHP classes. Traits work double duty: they say what a class can do (like an interface), and they provide a modular implementation (like class).编程

相对Android开发,我最喜欢的iOS中一个特性就是category,PHP的trait就是有点相似于category,不过仍是不太同样的:
1. OC只能针对特定的类进行扩展,而PHP的trait能够将代码单元注入到任意的不相关的类中;
2. 同时OC中的category并不能直接实现属性的扩展,而PHP的trait则能实现常量,属性,以及方法;
3. PHP的trait跟OC的category根本上来讲用途是不同的,OC是对现存类直接扩展,不须要继承实现类。而PHP的trait须要在类的定义中使用 use 来明确。

跟class和interface的定义同样,on trait per file

Generators

Generators are easy to create because they are just PHP functions that use the yield keyword one or more times. Unlike regular PHP functions, generators never return a value. They only yield values.

这个概念并不陌生,Python包括Swift都有这个特性,能够用在对大量数据的迭代中,动态去获取数据,而不是一次性生成,避免内存的浪费。

在每次迭代的过程当中,PHP都会让Generator实例计算和提供下一个迭代值。在这个过程当中,当generator执行到yield value的时候,generator会暂停它的内部状态的执行。只有generator被要求提供下一个迭代值的时候,它才会继续它的内部状态的执行。generator就这样反复pasuing 和 resuming,直到到达generator的函数定义的尾部或empty的时候,generator才会结束执行。

Generators are a tradeoff between versatility and simplicity. Generators are forward-only iterators.

Closures

A closure is a function that encapsulates its surrounding state at the time it is created. The encapsulated state exists inside the closure even when the closure lives after it original environment ceases to exist.

这里的闭包是指Closure和Anonymous functions。上面是做者对于闭包的解释,感受很是准确,比我看到的大多数解释都要简单清晰。闭包在平常业务开发中很是有用,能够很是方便替换咱们常常须要用到的delegate设计模式,不须要再去定义一个interface,而后再实现这个interface,再把对应的对象指针传递过去。而是经过Closure,只须要简简单单传递一段代码便可,这个极大简化了平常业务开发。因此目前iOS开发中,你们一般都会使用block来代替delegate设计模式。

PHP Closure or Anonymous function 跟PHP function的定义语法是同样的,可是实际上 Closure 的背后是Closure class的实例,因此Closure被认为是first-class value types。

Attach State : PHP的Closure不会automatically enclose application state,不像JavaScript/OC那样会capture做用域以外的变量。而是,you must manually attach state to a PHP closure with the closure object's bindTo() method or the use keyword.

须要注意的是,PHP closures是objects。而咱们之因此能让一个closure 实例变量进行调用,是由于这个对象实现 __invoke() magic method,当咱们在closure实例变量后面跟着一个 () 的时候,closure实例变量就会寻找而且调用__invoke() 方法,例如 $closure("Jason")

一样,因为PHP closure是objects。因此,在closure内部咱们也能够经过 $this 访问closure的各类内部状态,可是这个状态是很是boring。同时,closure的bindTo()方法能够有一些很是有趣的特殊用法,This method lets us bind a Closure object's internal state to a different object. The bindTo() method accepts an important second argument that specifies the PHP class of the object to which the closure is bound.This lets the closure access protected and private member variables of the object to which it is bound.。这个用法有点相似JavaScript的bind方法,能够改变Closure object的 $this 指针指向。

bindTo()这个有趣的用法,常常各类PHP框架的路由所采用,例如:

<? php class App { protected $routes = array(); protected $responseStatus = '200 OK'; protected $responseContentType ='text/html'; protected $responseBody = 'Hello world'; public function addRoute($routePath, $routeCallback) { // 将Closure bind到App类上 $this->routes[$routePath] = $routeCallback->bindTo($this, __CLASS__); } public function dispatch($currentPath) { foreach ($this->routes as $routePath => $callback) { if ($routePath === $currentPath) { $callback(); } } // 这里返回的state是在callback内修改过的 header('HTTP/1.1 '.$this.responseStatus); header('Content-type: '.$this.responseContentType); header('Content-length: '.mb_strlen($this->responseBody)); echo $this->responseBody; } } // 添加注册一个路由 <?php $app = new App(); $app->addRoute('/users/josh', function() { // 由于这个route是bindTo到App class上的,因此这里直接访问$this修改 App 的内部state $this->responseContentType = 'application/json;charset=utf8'; $this->responseBody = '{"name": "Josh"}'; }); $app->dispatch('/users/josh');

Zend Opcache

从PHP 5.5.0开始,PHP引入了内置的bytecode cache支持,叫作 Zend OPcache。PHP解释器在执行PHP脚本的时候,会首先把PHP代码编译为Zend Opcodes (machine-code instructions),而后才会执行bytecode。在全部请求中,PHP解释器都须要这样处理全部的PHP文件,read/parse/compiles,然而咱们能够经过把PHP文件预编为PHP bytecode来省略这个开销,这就是Zend OPcache

Zend OPcache的使用很是简单,在咱们配置以后,它就会在内存中自动缓存precompiled PHP bytecode,在可用的状况就会直接执行这个PHP bytecode,而不须要再去编译PHP代码。

具体配置去google吧,有一点须要注意的是,若是同时配置了 Xdebug的话,在php.ini文件中,须要在Xdebug以前加载Zend OPcache extension扩展。

Built-in HTTP server

PHP从5.4.0引入了内置的HTTP server,因此咱们在不配置Apache或者nginx的状况下就直接预览PHP程序。


Remember, the PHP built-in server is a web server. It speaks HTTP, and it can serve static assets in addition to PHP files. It's a great way to write and preview HTML locally without installing MAMP, WAMP, or a heavyweight web server.

要使用内置的HTTP server很是简单,在工程的根目录下,执行下面的命令便可:

php -S localhost:4000

若是要让本地网络的其余设备访问PHP web server,咱们能够这么启动:

php -S 0.0.0.0:4000

若是咱们但愿经过 PHP INI 配置文件去作一些特殊配置,能够经过下面命令来启动:

php -S localhost:8000 -c app/config/php.ini

咱们也能够经过Router Scripts来实现一些特殊的路由需求,能够经过下面的命令启动:

php -S localhost:8000 router.php

在PHP代码中,咱们能够经过php_sapi_name()来判断:

<?php if (php_sapi_name() === 'cli-server') { // PHP web server } else { // Other web server }

Part 2. Good Pratices

Standards

PHP-FIG

PHP-FIG (PHP Framework Interop Group): The PHP-FIG is a group of PHP framework representatives who, according to the PHP-FIG website, "talk about the commonalities between our projects and find ways we can work together."

PHP-FIG是由不少不一样PHP framework开发者组成的一个开放组织,他们提出的recommendations,不是标准或也不是要求,更像是best pratices的建议集合。不过,目前比较流行大可能是PHP框架,好比Laravel或Symfony,都遵照了这些recommendations,因此这个感受更像是Modern PHP事实上的标准,若是要使用PHP的不少工具和庞大的各类开源库,最好采用这个标准。

The PHP-FIG's mission is framework interoperability. And framework interoperability means working together via interfaces, autoloading, and style.
正以下面所说,PHP-FIG的使命就是不一样framework之间的互通,让不一样框架能够很容易结合在一块儿使用。而实现互通目前主要经过三个方面来入手:interfaces, autoloading, style:

  • Interfaces: Interfaces enable PHP developers to build, share, and use specialized components instead of monolithic frameworks,基于interfaces,咱们能够作到直接使用某个框架的某个组件,好比Laravel的HTTP的处理部分就是直接使用 Symfony Frameworks的 symfony/httpfoundation 组件,而不用把整个Symfony都集成到Laravel以内。
  • Autoloading: PHP frameworks work together via autoloading. Autoloading is the process by which a PHP class is automatically located and loaded on-demand by the PHP interpreter during runtime,在autoloading标准出来以前,PHP组件和框架都是基于 \__autoload()或spl_autoload_register() 方法来实现本身独特的autoloaders,因此咱们要使用一个第三方组件的时候,须要首先去研究一下它的autoloaders的实现。
  • Style: PHP frameworks work together via code style.

PSR

PSR是 PHP standards recommendation的缩写,是PHP-FIG提出的recommendations文档,例如PSR-1,PSR-2等。每一个PHP-FIG recommendation都是为了解决某个大多数PHP框架开发中常遇到的问题而提出的。

目前在PHP-FIG的官方网站上,http://www.php-fig.org/psr/ ,能够看到全部的recommendations,目前被采用的有下面几个:
这里写图片描述

具体的PSR文档内容,能够参考官方网站,PSR-1/2/3/4 几个文档有中文翻译:

文档 原文 中文翻译
PSR-1 Basic Coding Standard https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md http://www.javashuo.com/article/p-wrufwwbk-cv.html
PSR-2 Coding Style Guide https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md http://www.javashuo.com/article/p-vvialpdd-d.html
PSR-3 Logger Interface https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md http://www.javashuo.com/article/p-kesdlnex-gq.html
PSR-4 AutoLoading Standard https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md http://www.javashuo.com/article/p-bxlsflga-dh.html

PSR-1 Basic Coding standard

PHP tags : 使用

PSR-2 Strict Code Style

Implement PSR-1 : 要求必须采用PSR-1
Indentation: 采用4个空格字符做为缩进
Files and lines : 必须使用Unix linefeed(LF)做为结尾;文件最后必须以空行做为结束;不能使用尾部 ?> PHP tag;每行尽可能不要超过80个字符,最多不能超过120个字符;每行结尾不能包含空格;
Keywords: 全部的PHP关键字都必须小写
Namespaces: 每一个namespace声明后面都必须跟着一个空行;使用use来import or alias namespaces的时候,必须在use声明后面跟一个空行;
Classes: 定义类时,开始的大括号(opening bracket)必须新起一行,结束的大括号(closing bracket)必须在类体定义后面新起一行;extents/implements关键字必须跟在类名定义的后面;例如:

<?php namespace My\App; class Administrator extends User { // Class definition body }

Methods: 方法定义的大括号规则与类定义相似,opening brackets和closing brackets都必须新起一行。
Visibility: 对类中定义的所有property和method都必须声明可见性(visibility),可见性是public, protected, private其中的一个;abstract / final 必须写在visibility以前;static必须写在visibility以后;
Control structures : 全部的control structure keyword (if/elseif/else/switch/case/while/do while/for/foreach/try/catch)的后面都必须一个空字符;大括号的规则与class定义不一样,opening brackets跟control structure keyword必须在同一行,而closing bracket必须另新一行;

咱们能够经过IDE的格式化工具来让代码格式化,实现PSR-1和PSR-2的code style。我常用的工具PHPStorm就能够设置。还有一些其余工具,好比 PHP-CS-FixerPHP Code Sniffer

PSR-3 Logger Interface

PSR-3 is an interface, and it prescribes methods that can be implemented by PHP logger components.

PSR-4 Autoloaders

An autoloader is a strategy for finding a PHP class, interface, or trait and loading it into the PHP interpreter on-demand at runtime. PHP components and frameworks that support the PSR-4 autoloader standard can be located by and loaded into the PHP interpreter with only one autoloader.

关于PSR-4,看官方文档以后感受理解很困惑,本书的做者的解释就很是简洁:
The essence of PSR-4 is mapping a top-level namespaces prefix to a specific filesystem directory.,简单来讲,就是设定了一个namespaces前缀和某个特定的文件目录之间的映射关系,而后在这个namespace前缀之下若是还有更多的sub namespace,这些sub namespaces就会跟这个特定的目录下面的子目录一一映射起来。例如,\Oreilly\ModernPHP namespace与 src/ 物理路径一一映射,那么\Oreilly\ModernPHP\Chapter1对应的文件夹就是src/Chapter1,而\Oreilly\ModernPHP\Chapter1\Example类对应的文件路径就是src/Chapter1/Example.php文件。

PSR-4 lets you map a namespace prefix to a filesystem directory. The namespace prefix can be one top-level namespace. The namespace prefix can also be a top-level namespace and any number of subnamespaces. It's quite flexible.

Components

Components

Modern PHP is less about monolithic framework and more about composing solutions from specialized and interoperable components.

What Are Components?A component is a bundle of code that helps solve a specific problem in your PHP application.

框架与Components:若是咱们正在建立一个小项目,能够直接使用一些PHP Components集合来解决问题;若是咱们正在进行一个多人合做开发的大项目,咱们能够经过使用一个Framework;但这都不是绝对的,应该根据具体问题来解决。

Packagist:跟其余语言的包管理机制同样,例如Maven,也有一个网站 https://packagist.org/ 让咱们搜索咱们须要的PHP Components的相关信息。总所周知的缘由,Packagist在国内很不稳定,可使用国内的全量镜像来代替,http://www.phpcomposer.com/

Composer

Composer is a dependency manager for PHP components taht runs on the command line,跟其余现代语言同样,PHP使用Composer来作依赖管理,相似的有iOS中的Cocoapods,Android中的Maven/gradle,前端的npm,ruby的gem,这些工具能够大大简化咱们管理第三方库的成本。因而,当咱们在Packagist上面找到咱们须要的Components以后,就能够经过Composer来使用这个库。

当咱们使用Composer来添加第三方Component的时候,Composer除了会自动帮咱们下载须要的PHP Components以外,还会自动帮咱们建立一个符合PSR-4的Autoloader。

跟Cocoapods相似,Cocoapods使用Podfile来指定须要依赖的第三方库,以及保存有当前使用的具体的第三方库的版本号。因此咱们须要把这两个文件都加入到版本控制中进行管理,确保不一样成员/CI/开发环境等不一样地方你们使用第三方库版本的一致性。对应Composer中的文件就是 composer.json以及composer.lock。这里须要注意的是composer install 和 composer update 命令的差异:
* composer install,不会安装比composer.lock中列出的更高版本的Components;
* composer update,会更新你的components到最新的稳定版,同时也会更新composer.lock文件为最新的PHP components版本号。

Semantic Versioning

Modern PHP Components 使用 Semantic Versioning scheme,同时包含了用小数点(.)分隔的三个数字,好比 1.13.2。同时,这个也是不少其余语言开源库的版本规则,对这个一直比较好奇,终于在Modern PHP中看到了相应的解释。

  • major release number:第一个数字是major release number,只有当PHP Component发生再也不向前兼容的更新时,才须要增长这个版本号。
  • minor release number:第二个数字是minor release number,当PHP Component发生一些小的功能更新,而且没有破坏版本兼容时,增长这个版本号。
  • patch release number:最后一个数字是patch release number,当发生版本兼容的bug修复的时候,增长这个版本号。

Create PHP Components

这部分跟iOS建立本身的spec很是类似,并非很是复杂的问题,参考书或者官方文档很容易就能发布