Modern PHP reading notes one

Source: Internet
Author: User
Tags autoloader class definition function definition generator php class php framework php script visibility

About PHP, we have a lot of misunderstanding, but in fact, modern PHP is a door regardless of development efficiency or execution efficiency is quite high programming language. On the various aspects of modern PHP features, you can refer to the <modern php> author previously written PHP the right way, Chinese translation:php way . At the same time, the author is also the more popular PHP framework- Slim developers. So this book is worth reading, even if you only need to understand some OOP concepts, you do not need to understand PHP development.

Part 1 Language Feature Features namespaces helpful Tips Code to a interface Trait generators Closures Zend Opcache -in HTTP Server Part 2 good pratices standards Php-fig PSR PSR-1 Basic coding standard PSR-2 Strict Code Style PSR-3 Logge R Interface PSR-4 autoloaders components Components Composer-semantic Create PHP Versioning

Part 1. Language Feature Features namespaces

The PHP namespace uses the "\" character to split the sumnamespaces. Unlike the physical file system of the operating system, the PHP namespace is an abstract concept that does not have to correspond to the file directory one by one. Most PHP components organize subnamespaces and file directory mappings based on PSR-4 autoloader standard.

Technically, namespaces is just a symbol of a PHP language, which is used by the PHP interpreter as a prefix for a set of classes/interfaces/functions/constants sets.
Namespaces are important because they let us create sandboxed code this works alongside the other developer ' s code. This is the cornerstone concept of the modern PHP component ecosystem. Helpful Tips

1. Multiple Imports

<?php use


<?php use
Use Symfony\component\httpfoundation\response; 
Use Symfony\component\httpfoundation\cookie;

2. One class per file

3.Global Namespace
If we refer to a class/interface/function/constant,php that does not have a namespace, we will first assume that the class/interface/function/constant is in the current namespace. If not found in the current namespace, PHP will start resolve. For code that doesn't have namespaces, PHP thinks they exist in global namespace.

PSR-4 Code to an interface

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

A trait is a partial class implementation (i.e., constants, properties, and methods) which can be mixed to one or more Exi Sting PHP classes. Traits work Double Duty:they say what a class can do (like a interface), and they provide a modular implementation (like Class).

One feature of my favorite iOS, compared to Android development, is that category,php's trait is a bit like category, but it's not quite the same:
1. OC can only be extended for specific classes, and PHP's trait may inject the unit of code into any unrelated class;
2. At the same time the category in OC can not directly implement the extension of attributes, and PHP trait can implement constants, attributes, and methods;
3. PHP's trait is fundamentally different from OC's category, and OC is a direct extension of existing classes and does not need to inherit implementation classes. The trait of PHP needs to be used in the definition of the class to be clear.

As with class and interface definitions, ontrait per file. Generators

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

This concept is no stranger to Python, including Swift, which can be used to dynamically retrieve data in iterations of large amounts of data rather than one-time generation to avoid the waste of memory.

During each iteration, PHP lets the generator instance compute and provide the next iteration value. In this process, when generator executes to yield value, generator suspends execution of its internal state. Only when generator is required to provide the next iteration value does it continue execution of its internal state. Generator so repeatedly pasuing and resuming until it reaches the end of the function definition of generator or empty, generator will not finish execution.

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

A closure is a function this is the encapsulates it surrounding to the time it is created. The encapsulated state exists inside the closure even then closure lives after it original environment to ceases .

The closures here refer to closure and anonymous functions. This is the author's explanation for the closure, and it feels very accurate, much simpler than most of the explanations I've seen. Closures are useful in daily business development, and can be very handy for replacing delegate design patterns that we often need to use, without having to define a interface, then implement this interface, and then pass the corresponding object pointer over. Instead of simply passing a piece of code through the closure, this greatly simplifies day-to-day business development. So at present in iOS development, we usually use block to replace delegate design mode.

The PHP Closure or Anonymous function is the same as the definition syntax of the PHP function, but in fact Closure is the Closure class instance behind it, so Closure is considered first-class Value types.

Attach State: PHP closure does not automatically enclose application state, unlike JAVASCRIPT/OC, which capture variables outside the scope. Instead, you must manually attach state to a PHP closure with the closure object ' s BindTo () and the USE keyword.

It should be noted that PHP closures is objects. And the reason we can make a call to a closure instance variable is because the object implements __invoke () Magic method, and when we follow one () after the closure instance variable, the closure instance variable looks for and invokes the __ The Invoke () method, such as $closure ("Jason").

Again, because PHP closure is objects. Therefore, within the closure we can also access the various internal states of closure through $this, but this state is very boring. At the same time, the Closure bindto () method can have some very interesting special usages, this is lets us bind a Closure object ' internal state to a different object. The BindTo () method accepts a important second argument that specifies the PHP class of the object to which the closure I S bound. This lets the closure access protected, and private member variables of the "object to" which it is bound. This usage is a bit like the JavaScript bind method, which can change the $this pointer point of the closure object.

The interesting use of the

BindTo () is often used in a variety of PHP framework routes, such as:

    PHP class App {protected $routes = array ();
    protected $responseStatus = ' OK ';
    protected $responseContentType = ' text/html ';

    protected $responseBody = ' Hello world '; The Public Function Addroute ($routePath, $routeCallback) {//closure bind to the app class $this->routes[$routeP
    ATH] = $routeCallback->bindto ($this, __class__);
            Public Function Dispatch ($currentPath) {foreach ($this->routes as $routePath => $callback) {
            if ($routePath = = = $currentPath) {$callback ();
        The state returned here is the header (' http/1.1 '. $this responsestatus) that was modified within the callback.
        Header (' Content-type: $this. Responsecontenttype);
        Header (' Content-length: ' Mb_strlen ($this->responsebody));
    Echo $this->responsebody;
}//Add register a route <?php $app = new app (); $app->addroute ('/users/josh ', function () {//Because this route is bindto to App class, so here's a direct access to $this modify the app's interiorState $this->responsecontenttype = ' Application/json;charset=utf8 ';
$this->responsebody = ' {' name ': ' Josh '} ';
}); $app->dispatch ('/users/josh ');
Zend Opcache

Starting with PHP 5.5.0, PHP introduced the built-in bytecode cache support, called Zend Opcache. The PHP interpreter will first compile the PHP code into Zend opcodes (machine-code instructions) when executing the PHP script, and then execute the bytecode. In all requests, the PHP interpreter needs to handle all of the PHP files, read/parse/compiles, but we can omit this overhead by bytecode PHP files into PHP, which is Zend Opcache.

The use of Zend Opcache is very simple, after we configure, it will automatically cache in memory precompiled PHP bytecode, in the case of available will directly execute this PHP bytecode, and do not need to compile PHP code.

Specific configuration to go to Google, there is one thing to note is that if XDEBUG is configured at the same time, in the php.ini file, you need to load zend opcache extension extension before xdebug. built-in HTTP server

PHP introduces the built-in HTTP server from 5.4.0, so we preview the PHP program directly without configuring Apache or Nginx.

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, or a WAMP Web server.

To use the built-in HTTP server is very simple, under the root of the project, execute the following command:

Php-s localhost:4000

If you want to have other devices on the local network access the PHP Web server, we can start this way:


If we want to make some special configuration through the PHP INI configuration file, we can start with the following command:

Php-s localhost:8000-c App/config/php.ini

We can also implement some special routing requirements through router scripts, which can be started by using the following command:

Php-s localhost:8000 router.php

In the PHP code, we can use Php_sapi_name () to determine:

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's PHP framework representatives who, according to the Php-f IG website, "Talk about the commonalities between we projects and find ways we can work together."

Php-fig is an open organization made up of many different PHP framework developers, and their recommendations, not standard or not, is more like the best pratices proposal set. However, the current more popular is the PHP framework, such as Laravel or Symfony, have complied with these recommendations, so this feeling is more like modern php de facto standards, if you want to use a lot of PHP tools and a large variety of open source libraries, It is best to adopt this standard.


The Php-fig ' s mission is framework interoperability. and framework interoperability means working together via interfaces, autoloading, and style.
As mentioned below, the mission of Php-fig is to interoperate between different frameworks so that different frames can be used together easily. and realize interworking at present mainly through three aspects to start: interfaces, autoloading, style:Interfaces:Interfaces enable PHP developers to build, share, and use S pecialized components instead of monolithic frameworks, based on interfaces, we can do directly using a framework of a component, such as the Laravel HTTP processing part is the direct use of Symfony frameworks symfony/httpfoundation components without integrating the entire Symfony into 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 G Runtime, PHP components and frameworks are based on the \__autoload () or Spl_autoload_register () method to achieve their unique autoloaders before the autoloading standard, So when we want to use a third party component, we need to first study its autoloaders implementation. Style:php frameworks work together via code style. PSR

PSR is the abbreviation of PHP standards recommendation, the recommendations document presented by Php-fig, such as Psr-1,psr-2. Each Php-fig recommendation is proposed to address a common problem encountered in the development of a majority of PHP frameworks.

At present, on the official website of Php-fig, see all the recommendations, which are currently adopted in the following several:

The specific PSR document content, may refer to the official website, PSR-1/2/3/4 several documents to have the Chinese translation:

document original Chinese translation
P SR-1 Basic Coding Standard
psr- 2 coding Style Guide
PSR-3 L Ogger Interface
PSR-4 autoloading Standard
PSR-1 Basic Coding Standard

PHP tags : using PSR-2 Strict Code Style

implement PSR-1 : request must adopt PSR-1
indentation: use 4 whitespace characters as indentation
Files and lines : You must use UNIX linefeed (LF) as the end; The file must end with a blank line; You cannot use the tail?> PHP tag; try not to exceed 80 characters per line, up to 120 characters ; The end of each line cannot contain spaces;
Keywords: All PHP keywords must be lowercase
namespaces: After each namespace declaration must follow a blank line; When using use to import or alias namespaces, you must follow a blank line after the usage declaration;
Classes: When defining a class, the opening curly braces (opening bracket) must be a new row, and the closing curly braces (closing bracket) must be a new row behind the definition of the class body; extents/ The Implements keyword must be followed by the class name definition, for example:

namespace My\app;
Class Administrator extends User {
    //class definition body

Methods: The curly braces rules for method definitions are similar to class definitions, opening brackets and closing brackets must start a new row.
Visibility: All property and method defined in the class must declare visibility (Visibility), and visibility is public, protected, one of the private; abstract/ Final must be written before the visibility; the static must be written after visibility;
Control Structures : All control structure keyword (if/elseif/else/switch/case/while/do while/for/foreach/try /catch) must be followed by a null character; the rules of curly braces differ from class definitions, opening brackets with control structure keyword must be on the same line, and closing bracket must have another new row;

We can format the code with the IDE's formatting tools to implement the PSR-1 and PSR-2 codes style. I often use the tools phpstorm can be set. There are other tools, such as Php-cs-fixer or PHP Code Sniffer PSR-3 Logger Interface

PSR-3 is a interface, and it prescribes methods that can are implemented by PHP logger components. PSR-4 autoloaders

An autoloader was 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 is located by and loaded into the PHP INTERPR Eter with only one autoloader.

As for PSR-4, it is confusing to read the official document, and the author of this book has a very concise explanation:
The essence of PSR-4 is mapping a top-level namespaces prefix to a specific filesystem directory. In short, it's a namespaces prefix. And the mapping relationship between a particular file directory, and then under this namespace prefix if there are more sub namespace, these sub namespaces will be mapped to the subdirectory one by one below this particular directory. For example, \oreilly\modernphp namespace and src/physical path one by one mapping, then \oreilly\modernphp\chapter1 the corresponding folder is Src/chapter1, and \oreilly\ The file path corresponding to the Modernphp\chapter1\example class is the src/chapter1/example.php file.

PSR-4 lets your map a namespace prefix to a filesystem directory. The namespace prefix can be one top-level namespace. The namespace prefix can also is 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 compon Ents.

What Are components? : A component is a bundle of code this helps solve a specific problem in your PHP application.

Framework and Components: If we are creating a small project, we can use some of the PHP components set to solve the problem; if we are working on a large project that is being developed by many people, we can use a framework But this is not absolute and should be addressed on the basis of specific issues.

packagist: Like the package management mechanism in other languages, such as Maven, there is also a website lets us search for information about the PHP components we need. The general well-known reason, packagist in the domestic very unstable, can use the domestic full scale mirror to replace, Composer

Composer is a dependency manager for PHP components taht runs on the command line, like other modern languages, PHP uses Composer for dependency management, similar to C in iOS The Maven/gradle in Ocoapods,android, the Npm,ruby gem of the front end, these tools can greatly simplify the cost of managing Third-party libraries. Then, when we find the components we need on the packagist, we can use this library through composer.

When we use composer to add a third party component, composer will automatically help us to create a PSR-4 autoloader, in addition to automatically downloading the required PHP components.

Like Cocoapods, Cocoapods uses Podfile to specify Third-party libraries that need to be relied on, and to save the version number of a specific Third-party library that is currently in use. So we need to add all two files to the version control to make sure that the consistency of Third-party library versions is used in different places, such as/ci/development environment. The files in the corresponding composer are Composer.json and Composer.lock. Note the difference between the composer install and composer update commands:
* Composer Install, will not install a higher version than the components listed in Composer.lock;
* Composer Update updates your components to the latest stable version and updates the Composer.lock file as the latest PHP components version number. Semantic Versioning

Modern PHP components uses semantic Versioning scheme and includes a decimal point (.) Separated by three digits, such as 1.13.2. At the same time, this is also a lot of other languages open Source Library version rules, this has been more curious, and finally in modern PHP see the corresponding explanation. Major release number: The first digit is major releases number, which is only required if the PHP component occurs without a forward-compatible update. Minor release number: The second digit is minor releases number, which is incremented when the PHP component has some minor feature updates and does not break version compatibility. Patch release Number: The last digit is patch releases number, which is incremented when a version-compatible bug fix occurs. Create PHP Components

This part is very similar to iOS creating its own spec, and it's not a very complex issue, and it's easy to publish reference books or official documents.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.