Traits, generators, closures, Opcache "modern PHP"

Source: Internet
Author: User
Tags php class sprintf traits

Directory

    • Trait Trait
    • Generator
    • Closed Package
    • Zend Opcache

PHP development for so many years, technology, architecture has been revolutionized, understand the modern PHP is very important, recently in the model PHP this book, the system to understand the concept of PHP-related.

Trait Trait

is a partial implementation of a class (that is, constants, properties, and methods) that can be mixed into one or more existing PHP classes.
Traits have two functions: indicate what the class can do (interfaces), and provide a modular implementation (like a class).

For example, two unrelated classes need to have a common approach, inheritance, interfaces are not very reasonable (first, the attributes are different, the second is code duplication), using traits can use a method together.

For example, cars and couriers may all need to find a location

trait Geocodable{    protected $address;    protected $geocoder    //获取经纬度    public function getLatitude(){    }}

Usage traits:

<?phpClass Car{    use Geocodable;    //类的实现    ...}
Generator

The generator provides an easier way to implement a simple object iteration, comparing the way in which you define a class to implement a Iterator interface (normal iteration), with significantly reduced performance overhead and complexity.

The generator allows you to write code in a foreach code block to iterate over a set of data without having to create an array in memory, which will limit your memory to a maximum or take up considerable processing time. Instead, you can write a generator function, just like a normal custom function, and the normal function returns only once differently, and the generator can yield multiple times as needed to generate values that need to be iterated.

The generator calculates the values to iterate on demand, calculates and outputs subsequent values in a timely manner, without consuming valuable memory resources.

A simple example is to use the generator to re-implement the range () function. The standard range () function needs to generate an array in memory that contains every value within its scope, and then returns the array, resulting in multiple large arrays. For example, calling range (0, 1000000) will result in memory consumption exceeding MB.

As an alternative, we can implement a xrange () generator that requires only enough memory to create the Iterator object and keep track of the generator's current state internally, which requires less than 1K bytes of memory.

Example #1 to implement range () as the generator

<?phpfunction xrange($start, $limit, $step = 1) {    if ($start < $limit) {        if ($step <= 0) {            throw new LogicException('Step must be +ve');        }        for ($i = $start; $i <= $limit; $i += $step) {            yield $i;        }    } else {        if ($step >= 0) {            throw new LogicException('Step must be -ve');        }        for ($i = $start; $i >= $limit; $i += $step) {            yield $i;        }    }}/* * 注意下面range()和xrange()输出的结果是一样的。 */echo 'Single digit odd numbers from range():  ';foreach (range(1, 9, 2) as $number) {    echo "$number ";}echo "\n";echo 'Single digit odd numbers from xrange(): ';foreach (xrange(1, 9, 2) as $number) {    echo "$number ";}?>

The above routines will output:

Single digit odd numbers from range():  1 3 5 7 9Single digit odd numbers from xrange(): 1 3 5 7 9

Imagine processing a Fibonacci sequence or an iterative flow resource, assuming that a 4GB CSV file is processed, and the virtual server only allows 1GB of memory, and if the entire load is in memory, the server will collapse, and the generator will only allocate memory for the CSV row at a time.

<?php    function getRows( $file ){        $handle = fopen($file,'rb');        if( $handle === false ){            throw new Exception();        }        while(feof($handle) === false){            yield fgetcsv($handle);        }        fclose($handle);    }    foreach($getRows('data.csv') as $row){        print_r($row);    }

Generators are the solution between functional diversity and simplicity. The generator is a forward-only iterator that cannot perform fast forward, backward, or lookup operations.

See the article by Bird Brother: http://www.laruence.com/2015/05/28/3038.html

Closed Package

is a function that encapsulates the surrounding state at the time of creation.
An anonymous function is actually a function that has no name, and is particularly well-suited as a function or method invocation.

    • The method is called automatically when _invoke attempts to invoke an object in a functional manner.

Create a simple closure

$closure = function($name){    return sprintf ('hello %s',$name);}echo $closure("Josh");//输出 --> hello Josh

As a callback

//匿名回调$numbersPlusOne = array_map(function( $number ){    return $number+1;},[1,2,3]);print_r($numbersPlusOne);//输出  --> [2,3,4]
//具名回调function incrementNumber($number){    return $number+1;}$numbersPlusone = array_map('incrementNumber',[1,2,3]);print_r($numbersPlusOne);//输出  --> [2,3,4]
    • Attach Status

PHP closures attach and encapsulate the state, manually invoke the BindTo () method of the closure object or use the Using keyword to attach the state to the PHP closure.

Instance:

<?phpfunction enclosePersion( $name ){    return function($doCommand use $name){        return sprintf('%s,%s',$name,$doCommand);    }}//将字符串“sun”封装到闭包中$sun = enclosePersion( 'sun' );//传入参数,调用闭包echo $sun('get me sweet tea!');//输出  --> "sun,get me sweet tea!"

PHP closures are objects, similar to any other PHP object, and each closure instance can use the $this keyword to get the internal state of the closure. Closures have __invoke (), BindTo () methods;

    • [] Refer to the manual, manual has detailed description bindto, bind;
<?php class  A  {    function  __construct ( $val ) {         $this -> val  =  $val ;    }    function  getClosure () {         //returns closure bound to this object and scope         return function() { return  $this -> val ; };    }} $ob1  = new  A ( 1 ); $ob2  = new  A ( 2 ); $cl  =  $ob1 -> getClosure ();echo  $cl (),  "\n" ; $cl  =  $cl -> bindTo ( $ob2 );echo  $cl (),  "\n" ; ?>以上例程的输出类似于:12
Zend Opcache

Starting with PHP 5.5.0, the bytecode caching feature is built in.
PHP Execution Process:

graph LR解析脚本代码-->编译成一系列Zend操作码编译成一系列Zend操作码-->执行字节码

The bytecode cache stores pre-compiled PHP bytecode, and the PHP interpreter skips reading, parsing, compiling PHP code, reading precompiled bytecode directly from memory, and executing. The benefits save time and greatly enhance the performance of your application.

    • Enable Zend Opcache

When compiling PHP, explicitly specify enable Zend Opcache.
The following options must be included when executing the./configure command:

--enable-opcache

Successful compilation displays the file path of the Zend Opcache extension. You can also find an extended installation path by using the following command

php-config --extension-dir

The Zend Opcache extension path is specified in the php.ini file, such as:

zend_extension=/path/to/opcache.so

Update the php.ini file and restart the PHP process.

<?php    phpinfo()

View Zend Opcache Extension Open condition

    • Configuring Zend Opcache
[Opcache]zend_extension=/usr/local/php5/lib/php/extensions/no-debug-non-zts-20131226/opcache.so; Zend Optimizer + switch, code is no longer optimized when off. opcache.enable=1; Determines if Zend Opcache is enabled for the CLI version of Phpopcache.enable_cli=1; Zend Optimizer + Shared memory size, total ability to store how much precompiled PHP code (in MB), according to memory to set the opcache.memory_consumption=256; Zend Optimizer + The total memory of the string in the staging pool. (unit: MB); Recommended 8opcache.interned_strings_buffer=4; Maximum number of cached files between 200 and 100000; Recommended 4000~8000opcache.max_accelerated_files=8000; Memory "Wasted" reaches the percentage corresponding to this value, a restart schedule is initiated. opcache.max_wasted_percentage=5; Open this command, Zend Optimizer + will automatically append the name of the current working directory to the script key; This eliminates key-value naming conflicts between files of the same name. Closing this command will improve performance; However, it can cause damage to existing applications. Opcache.use_cwd=0; Open file timestamp verification Opcache.validate_timestamps=1; 2s Checking for file updates Note: 0 is always checked not off; Recommended 60opcache.revalidate_freq=0; Allow or prohibit the optimization of file search in include_path; opcache.revalidate_path=0; Whether to save comments on file/function if Apigen, Doctrine, ZF2, phpunit need file comment; Recommended 0opcache.save_comments=1; Whether to load the comments of the file/function; Opcache.load_comments=1; Turn on quick close, open this when PHP Request shutdown the memory will be increased; Recommended 1OPCACHE.FAST_SHUTDOwn=1 the optimization feature that allows overwriting of file presence (file_exists, etc.). ; opcache.enable_file_override=0; Define how many optimization processes to start; opcache.optimization_level=0xffffffff; Enabling this hack can temporarily resolve the "can ' t Redeclare class" error.; o pcache.inherited_hack=1; Enabling this hack can temporarily resolve the "can ' t Redeclare class" error.; o pcache.dups_fix=0; Set a blacklist that does not cache; PHP files beginning with cache_ in the specified directory are not cached. /png/www/example.com/public_html/cache/cache_;opcache.blacklist_filename=; The cache of large files is removed through the file size screen. By default, all files are cached.; o pcache.max_file_size=0; Check cache checksum once per N requests. The default value of 0 indicates that the check is disabled.; Due to the calculation of the checksum lossy performance, this directive should be tightly opened at the time of development debugging. O pcache.consistency_checks=0; When the cache is not accessed, the wait time (in seconds) for the scheduled restart; opcache.force_restart_timeout=180; The error log file name. Empty indicates the use of standard error output (stderr).; o Pcache.error_log=/tmp/ckl.log; Write error message to server (Apache etc) log; opcache.log_verbosity_level=1; The preferred background for memory sharing. Leave blank to let the system choose.; o pcache.preferred_memory_model=; Prevent accidental writes during script execution within a share, for internal debugging only.; o Pcache.protect_memory=0

Refer to the configuration of the great God

opcache.enable=1opcache.memory_consumption=256opcache.interned_strings_buffer=4opcache.max_accelerated_files=8000opcache.max_wasted_percentage=5opcache.use_cwd=1opcache.validate_timestamps=1opcache.revalidate_freq=0opcache.revalidate_path=0opcache.save_comments=0opcache.load_comments=0opcache.force_restart_timeout=3600

Traits, generators, closures, Opcache "modern PHP"

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: info-contact@alibabacloud.com 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.