Do you really know PHP now?

Source: Internet
Author: User
Tags php framework traits what interface
Some time ago, the company's project from"target=" _blank ">php5.3 upgrade to PHP7, now the project began to use some of the new PHP7 syntax and features. The 5.4, 5.5, and 5.6 versions of PHP have a somewhat cognitive sense of missing. So, decided to see the "modern PHP" complement a few of the concepts inside.

I'm reading this book.

First, the characteristics

1. Namespaces

Namespaces use more, not detailed, and record a few noteworthy practices and details.
Multiple imports
Don't do that, it's confusing to write.

<?phpuse symfony\component\httpfoundation\request,    symfony\component\httpfoundation\response,    Symfony\component\httpfoundation\cookie;

We recommend that you write a use statement on one line:

<?phpuse Symfony\component\httpfoundation\request;use Symfony\component\httpfoundation\response;use Symfony\ Component\httpfoundation\cookie;

Use multiple namespaces in one file
You can do this, but this violates the good practice of "A file defines a class" .

<?phpnamespace Foo {  //code}namespace Bar {  //code}

Global namespaces
To use PHP's native exception class, you need to add \ Symbols before the class name.

<?phpnamespace my\app;class foo{public  function dosomething ()  {    $exception = new \exception ();}  }

If the exception is not added before the \ symbol, the exception class is searched under the My\app namespace.

2. Using the interface

The code written with the interface is more flexible and can delegate other people to implement the details. The person you use only needs to care about what interface you have, without needing to care about the implementation. Can be well decoupled code, easy to expand, more often than not said.

3. Traits

The traits (trait) were not clear until the Laravel framework was studied. This is a new concept introduced by PHP5.4.0, both as a class and as an interface. But neither of them is.

A trait is a partial implementation of a class that can be mixed into one or more existing PHP classes. A combination of ruby-like modules is mixed (mixin).

Why use traits
For example, there are two classes, Car and Phone, all of which require GPS functionality. To solve this problem, the first reaction is to create a parent class, and then let car and phone inherit it. But because it is clear that this ancestor does not belong to the respective inheritance hierarchy.

The second reaction creates a GPS interface, defines the function interface of the GPS, and then enables the car and phone two classes to implement this interface. This enables functionality, while maintaining a natural hierarchy of inheritance. However, this makes it possible to replicate the GPS function in all two, which does not conform to the dry (dont repeat yourself) principle.

The third reaction is to create traits that implement the GPS function (trait), and then mix this trait in car and phone classes. Can realize the function, does not affect the inheritance structure, does not repeat realizes, is perfect.

Creating and using traits
Create trait

<?phptrait mytrait{  //implementation}

Using trait

<?phpclass myclass{use  mytrait;  Implementation of the class}

4. Generator

PHP Builder (Generator) is a new feature introduced by PHP5.5.0 and is not known by many PHP developer generators. The generator is a simple iterator, but the generator does not require the implementation of the iterator interface. The generator calculates and produces the values to iterate as needed. If you do not query, the generator never knows what the next iteration value is and cannot rewind or fast forward in the generator. See the following two examples:

A simple generator

<?phpfunction Makerange ($length) {for  ($i = 0; $i < $length; $i + +) {    yield $i;  }} foreach (Makerange (1000000) as $i) {  echo $i, Php_eol;}

Scenario: Using the generator to process a CSV file

<?phpfunction getRows ($file) {  $handle = fopen ($file, ' RB ');  if ($handle = = = False) {    throw new Exception ();  }  while (feof ($handle) = = = False) {    yield fgetcsv ($handle);  }} foreach (GetRows (' data.csv ') as $row) {  print_r ($row);}

To deal with this scenario, the customary approach is to first read all the contents of the file into the array, then do the processing, and so on. The problem with this approach is that when the file is extremely large, a single read consumes a lot of memory resources. The generator is best suited for this scenario because it takes up a very small amount of system memory .

5. Closures

In theory, closures and anonymous functions are different concepts. However, PHP sees it as the same concept.
Simple closures

<?php$closure = function ($name) {  return sprintf (' Hello%s ', $name);} Echo $closure ("Beck");//output--"Hello Beck"

Note: We can invoke the $closure variable because the value of the variable is a closure, and the closure object implements the Invoke () Magic method. As long as the variable name is followed by (), PHP will find and invoke the Invoke () method.

Attach Status
Using the Use keyword allows you to pass multiple arguments to a closure, which, like the parameters of a PHP function or method, separates multiple parameters with commas.

<?phpfunction Encloseperson ($name) {  return function ($doCommand) use ($name) {    return sprintf ('%s,%s ', $ Name, $doCommand);}  ;} Enclose the string "Clay" in the closure $clay = Encloseperson (' Clay ');//incoming parameter, call the closure echo $clay (' Get Me Sweet tea! '); /output--"Clay, Get Me Sweet tea!"

Use the BindTo () method to attach the state of a closure
The PHP framework often uses the BindTo () method to map a route URL to an anonymous callback function, which binds an anonymous function to an Application object, which can be used to refer to an important Application object using the $this keyword in this anonymous function. Examples are as follows:

<?phpclass app{  protected $routes = Array ();  protected $responseStatus = ' OK ';  protected $responseContentType = ' text/html ';  protected $responseBody = ' Hello world ';  Public Function Addroute ($routePath, $routeCallback)  {    $this->routes[$routePath] = $routeCallback BindTo ($this, CLASS);//Focus  } public  function Dispatch ($currentPath)  {    foreach ($this->routes as $ Routepath = $callback) {      if ($routePath = = = $currentPath) {        $callback ();      }    }    Header (' http/1.1 '. $this->responsestatus);    Header (' Content-type: '. $this->responsecontenttype);    Header (' Content-length '. Mb_strlen ($this->responsebody));    echo $this->responsebody;  }}

Line 11th is where the focus is, binding the routing callback to the current app instance. Doing so can handle the status of the app instance in the callback function:

<?php$app = new app (); $app->addroute ('/users/josh ', function () {  $this->responsecontenttype = ' Application/json;charset=utf8 ';  $this->responsebody = ' {' name ': ' Josh '} ';}); $app->dispatch ('/users/josh ');

6. Zend Opcache

Byte-code caching is not a new feature of PHP, and many independent extensions can implement caching. Starting with PHP5.5.0, PHP has built-in bytecode caching, called Zend Opcache.

What is a byte-code cache?
PHP is an explanatory language, PHP interpreter executes PHP script will parse the PHP script code, the PHP code compiled into a series of Zend opcode, and then execute the byte code. Every time a PHP file is requested, it consumes a lot of resources. Bytecode caches can store pre-compiled PHP bytecode. This means that the PHP interpreter does not have to read, parse, and compile PHP code every time the PHP script is requested. This can greatly improve the performance of your application.

7. Built-in HTTP server

PHP has built-in Web servers from PHP5.4.0, which can be a hidden feature for many PHP developers who use Apache or Nginx. However, this built-in server is not fully functional and should not be used in a production environment, but is a handy tool for local development and can be used to quickly preview some frameworks and applications.

Start the server

Php-s localhost:4000

Configure the server

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

Router Script
Unlike Apache and Nginx, it does not support. htaccess files. Therefore, it is difficult for this server to use the front-end controllers common in most popular PHP frameworks. PHP's built-in server uses router scripting to compensate for this missing feature. The router script is passed before each HTTP request is processed, and if the result is false, returns the static resource URI referenced in the current HTTP request.

Php-s localhost:8000 route.php

is a built-in server

<?phpif (php_sapi_name () = = = ' Cli-server ') {  //php built-in Web server}
Related Article

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.