PHP怎么做服务化?


难道只能用http的方式提供API吗?

http php 服务化 api

大废柴教VIP 11 years, 2 months ago

PHP不一定要以http方式调用。PHP与其它应用的接口叫做SAPI,选用不同的SAPI决定了调用PHP的方式。例如Apache的mod_php就是一个SAPI的实现,用于Apache与PHP交互,同样,CGI和FastCGI(如fpm)的SAPI实现也是用于以HTTP方式调用PHP解释器。
除此之外,还有很多SAPI,如CLI的SAPI可以支持命令行方式运行PHP脚本,运用php的pcntl_fork函数可以用与C类似的方式(两次fork)创建deamon进程,这样PHP脚本就可以当做服务使用了。
至于服务与其它进程的交互,php支持socket。
我写过一个小的Demo,展示了如何用PHP写Server,你可以看一下:

<?php

//Accpet the http client request and generate response content.
//As a demo, this function just send "PHP HTTP Server" to client.
function handle_http_request($address, $port)
{
    $max_backlog = 16;
    $res_content = "HTTP/1.1 200 OK\nContent-Length: 15\nContent-Type: text/plain; charset=UTF-8\n\nPHP HTTP Server
    ";
    $res_len = strlen($res_content);

    //Create, bind and listen to socket: 127.0.0.1:8888
    if(($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE)
    {
        echo "Create socket failed!\n";
        exit;
    }   

    if((socket_bind($socket, $address, $port)) === FALSE)
    {
        echo "Bind socket failed!\n";
        exit;
    }

    if((socket_listen($socket, $max_backlog)) === FALSE)
    {
        echo "Listen to socket failed!\n";
        exit;
    }

    //Loop
    while(TRUE)
    {
        if(($accept_socket = socket_accept($socket)) === FALSE)
        {
            continue;
        }
        else
        {
            socket_write($accept_socket, $res_content, $res_len);   
            socket_close($accept_socket);
        }
    }
}

//Run as deamon process.
function run()
{
    if(($pid1 = pcntl_fork()) === 0)
    //First child process
    {
        posix_setsid(); //Set first child process as the session leader.

        if(($pid2 = pcntl_fork()) === 0)
        //Second child process, which run as deamon.
        {
            handle_http_request('www.codinglabs.org', 9999); //Replaced by your own domain or address.
        }
        else
        {
            //Second child process exit;
            exit;
        }
    }
    else
    {
        //First child process exit;
        pcntl_wait($status);
    }
}

//Entry point.
run();

?>
西西西子酱 answered 11 years, 2 months ago

Your Answer