PHP code example of hetao29 / php-grpc-server-protobuf

1. Go to this page and download the library: Download hetao29/php-grpc-server-protobuf library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hetao29 / php-grpc-server-protobuf example snippets



define("ROOT",				dirname(__FILE__)."/../");
define("ROOT_LIBS",			ROOT."/libs");
define("ROOT_APP",			ROOT."/app");
define("ROOT_PROTO_GENERATED",		ROOT."/proto_generated");
ter(function($class){
	$root = ROOT_APP."/".str_replace("\\","/",$class).".php";
	if(is_file($root)){
		


ne("ROOT",				__DIR__."/../");
define("ROOT_APP",			__DIR__."/../app");
define("ROOT_PROTO_GENERATED",		__DIR__."/../proto_generated/");
spl_autoload_register(function($class){
	$root = ROOT_PROTO_GENERATED."/".str_replace("\\","/",$class).".php";
	if(is_file($root)){
		equest, Swoole\Http\Response $response) use ($http) {
	$content_type = (isset($request->header['content-type']) && $request->header['content-type']=='application/json') ? 'json' : null; //json | null (default)
	if($content_type=="json"){
		$response->header('content-type', 'application/json');
	}else{
		$response->header('content-type', 'application/grpc');
	}
	try{
		if(($r=GRpcServer::run($request->server['request_uri'], $request->rawContent(), $content_type))!==false){
			//echo($r);
			$response->header('trailer', 'grpc-status, grpc-message');
			$trailer = [
				"grpc-status" => "0",
				"grpc-message" => ""
			];
			foreach ($trailer as $trailer_name => $trailer_value) {
				$response->trailer($trailer_name, $trailer_value);
			}
			$response->end($r);
	}
	}catch(Exception $e){
		$response->header('trailer', 'grpc-status, grpc-message');
		$trailer = [
			"grpc-status" => $e->getCode(),
			"grpc-message" => $e->getMessage(),
		];
		foreach ($trailer as $trailer_name => $trailer_value) {
			$response->trailer($trailer_name, $trailer_value);
		}
		$response->end();
	}
});
$http->start();



namespace Test\Helloworld;
class Greeter implements GreeterInterface{
	/**
	 */
	public function SayHello(HelloRequest $request) : HelloReply{
		$reply = new HelloReply();
		$reply->setMessage("Hello2, ".$request->getName()."!");
		return $reply;
	}
}