Deep understanding of the PHP Kernel (ii) SAPI Explore _php examples

Source: Internet
Author: User
Tags data structures fpm garbage collection memcached php memcached php script sapi zend

In the previous article to introduce you to the in-depth understanding of the PHP kernel (i), I believe that we have learned more or less some knowledge of the PHP kernel knowledge continue to focus on this article.

SAPI is the abbreviation for the server Application programming Interface (the application programming interface for servers). PHP provides a set of interfaces through SAPI for data interaction between the application and the PHP kernel.

In simple terms, just like the input and output of a function, we execute a section of PHP code through the Linux command line, which is essentially a Linux shell that passes through PHP's SAPI to a set of parameters that the Zend engine executes and returns to the shell, which is displayed by the shell. Similarly, through Apache invoke PHP, through the Web server to SAPI incoming data, Zend engine execution, returned to Apache, by the Apache display on the page.


Figure 1. PHP Frame composition

PHP offers many forms of interface, including Apache, Apache2filter, Apache2handler, Caudium, CGI, cgi-fcgi, CLI, cli-server, continuity, embed, ISAPI , Litespeed, Milter, Nsapi, phttpd pi3web, Roxen, thttpd, Tux and Webjames. But there are only 5 forms commonly used, cli/cgi (command line), multiprocess (multiple processes), multithreaded (multithreading), fastcgi, and embedded (inline).

PHP provides a function to view the current SAPI interface type:

Copy Code code as follows:

String Php_sapi_name (void)

Running and loading of PHP

Regardless of which SAPI is used, before and after PHP executes a script, it contains a series of events: Init (MINT) and shutdown (mshutdown) of module, Init (RINT) of the Request, and shutdown (Rshutdown). The first phase is the PHP module initialization phase (MINT), which allows you to initialize extended internal variables, allocate resources, and register resource processors, which are executed only once throughout the life cycle of the PHP instance.

What is a PHP module? With the above PHP frame composition, you can use the Get_loaded_extensions function in PHP to view all the compiled and loaded modules/extensions, equivalent to the php-m in CLI mode.

Take the PHP memcached extended source code as an example:

Php_minit_function (memcached) { 
 zend_class_entry ce; 
 memcpy (&memcached_object_handlers,zend_get_std_object_handlers (), sizeof (zend_object_handlers)); 
Memcached_object_handlers.clone_obj = NULL; /* Some similar initialization operation was performed/* return 
SUCCESS; 
}

The second stage is the request initialization phase (RINT), which creates a PHP runtime environment when the module is initialized and activated, invokes all module-registered RINT functions, invokes each extended request initialization function, sets specific environment variables, allocates resources, or performs other tasks, such as auditing.

Php_rinit_function (memcached) {/ 
 * performs some initialization of the request/return 
 SUCCESS; 
}

In the third phase, when the request processing is complete, the php_rshutdown_function is invoked for recycling, which is the request shutdown function for each extension to perform the final cleanup. The Zend engine performs the cleanup process, garbage collection, and executes unset for each variable used during the previous request. The completion of the request may be done to the script, or the call to die () or the exit () function completes

Phase IV, when the PHP lifecycle ends, php_mshutdown_function the module for recycling, which is an extended module shutdown function that shuts down its own kernel subsystem.

Php_mshutdown_function (memcached) {/* Execute the destruction work on the module/unregister_ini_entries (); return SUCCESS;}

Common mode of Operation

There are five common SAPI modes:

CLI and CGI mode (single process mode)
Multi-process Mode
Multithreading mode
fastcgi mode
Embedded

1. cli/cgi mode

Both CLI and CGI are part of a single process mode, and the life cycle of PHP is completed in one request. That is, every time you execute a PHP script, you execute the four int and shutdown events in the second section.

Figure 2. CGI/CLI life cycle

2. Multi-process mode (multiprocess)

Multi-process mode can be built into the Web server PHP, PHP can be compiled into Apache under the Prefork mpm mode and APXS module, when the Apache started, will fork many child processes, each child process has its own separate process address space.


Figure 3. Multi-process mode life cycle

In a subprocess, the life cycle of PHP is to invoke the Mint startup, execute multiple requests (Rint/rshutdown), and then invoke the Mshutdown for the recycle phase after the Apache shutdown or process ends.

Figure 4. Life cycle of multiple processes

In a multi-process model, each subprocess is run independently, without code and data sharing, so a child process terminates the exit and regeneration without affecting the stability of other child processes.

3. Multithreading mode (multithreaded)

The Apache2 worker MPM employs a multithreaded model that creates multiple threads under one process and executes in the same process address space.


Figure 5. Multithreaded lifecycle

4. FastCGI mode

In our use of the NGINX+PHP-FPM is the fastcgi mode, fastcgi is a special CGI mode, is a resident process type of CGI, after running can fork multiple processes, do not spend time dynamic fork child processes, Mint/mshutdown is also not required to be invoked on each request. PHP manages and dispatches the fastcgi process pool through PHP-FPM. Nginx and PHP-FPM communicate through a local TCP socket and a UNIX socket.


Figure 6. FastCGI Mode life cycle

PHP-FPM the process manager itself, initiating multiple CGI interpreter processes to wait for requests from Nginx. When the client request reaches PHP-FPM, the manager selects a CGI process for processing, Nginx sends the CGI environment variable and standard input to a php-cig subprocess. When the php-cgi process completes, the standard output and error messages are returned to Nginx, and the request processing completes when the php-cgi child process closes the connection. The php-cgi child process waits for the next connection.

You can imagine how much the CGI system overhead is. Each Web request PHP must reparse php.ini, load all extensions, and start all data structures. With fastcgi, all of these occur only once when the process is started. In addition, continuous connections to the database and memcache can work.

5. Inline mode (Embedded)

Embed SAPI is a special SAPI that allows you to invoke PHP-supplied functions in the C + + language. This sapi, like the CLI mode, runs in the mode of module init => request Init => request => request Shutdown => Module Shutdown.

Embed SAPI can invoke PHP's rich library of classes, as well as advanced gameplay, such as viewing php's opcode (php-Executed middle code, Zend-engine instructions, generated by PHP code).

Detailed See: http://www.jb51.net/article/74641.htm

The operating mechanism of SAPI

Let's take a CGI example and look at the operating mechanism of SAPI.

Static Sapi_module_struct Cgi_sapi_module = {"cgi-fcgi",/* output to Php_info () use/"cgi/fastcgi", * * Pretty name * * * Php_cgi_startup,/* startup when SAPI initializes, the function is called first/php_module_shutdown_wrapper,/* Shutdown closes the function wrapper, which is used to release all SAPI data structures, Save, call Php_module_shutdown/sapi_cgi_activate,/* Activate this function will be invoked at the start of each request, it will do initialization, resource allocation/sapi_cgi_deactivate,/* DEA Ctivate This function is invoked at the end of each request to ensure that all data is released/Sapi_cgi_ub_write,/* unbuffered write does not cache writes (unbuffered write), which is used to SAPI external Output data */Sapi_cgi_flush,/* Flush refresh output, in CLI mode by using the C language library function Fflush implementation/NULL, * get UID/sapi_cgi_getenv,/* Geten V to find environment variables according to name/php_error,/* Error handler registration fault handling function/NULL,/* Header handler PHP call header () when called * * SAPI_CG  I_send_headers,/* Send headers handler sends header message * * NULL,/* Send header handler sends a separate header message * * * sapi_cgi_read_post, /* Read post data when the method of the request is post, the program gets the post, writes the $_post array/sapi_cgi_read_cookies,/* Read cookies get the cookie value * * sapi_cgi_ Register_variables, * regIster Server variables Add environment variable to $_server/sapi_cgi_log_message,/* Log message Output error messages/NULL,/* GET request time  * * NULL,/* Child terminate * * standard_sapi_module_properties};

As you can see from the above code, PHP's SAPI are like object-oriented base classes, SAPI.h and SAPI.C contain functions that are the declaration and definition of abstract base classes, and the SAPI pattern used by each server is to inherit the base class and redefine the subclass of the base class method.

Summarize

PHP's SAPI is a set of standard interfaces provided by the Zend engine, which enables us to run the application on the Zend engine or embed PHP in a Web server like Apache by registering an interface such as initialization, destructor, input, and output. There are five common sapi patterns in PHP, CGI/CLI mode, multi-process mode, multithreaded mode, fastcgi mode, and inline mode.

Understanding the SAPI mechanism of PHP is important to help us understand the lifecycle of PHP, and to learn how to better write extensions to PHP through C + +, and find ways to improve system performance throughout the lifecycle.

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.