PHP code example of austp / php-graphql

1. Go to this page and download the library: Download austp/php-graphql 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/ */

    

austp / php-graphql example snippets

(php)


new GraphQL\Server('/path/to/schema.graphql');

$server->register('hello', function () {
    return 'Hello World!';
});

$query = '{
    hello
}';

$response = $server->handle($query);
print(json_encode($response));
(php)
$server->register('echo', function ($args) {
    return $args['message'];
});

$query = '{
    ping: echo(message: "Ping!")
    pong: echo
}';
(php)
$query = 'query PingPong($one: String, $two: String = "Two!", $three: String) {
    one: echo(message: $one)
    two: echo(message: $two)
    three: echo(message: $three)
}';

$variables = ['one' => 'One!'];

$response = $server->handle($query, $variables);
(php)
class Human
{
    use GraphQL\Schema\ResolverTrait;

    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    protected function resolve($fieldName, $args)
    {
        if ($fieldName === 'name') {
            return $this->name;
        } elseif ($fieldName === 'friends') {
            return [
                new self('Adolin'),
                new self('Dalinar')
            ];
        }
    }
}
(php)
$server->register('kaladin', function () {
    return new Human('Kaladin');
});

$query = '{
    kaladin {
        name
        friends {
            name
        }
    }
}';
(php)
$server->register('kaladin', function () {
    return new GraphQL\Schema\Resolver(function ($fieldName, $args) {
        if ($fieldName === 'name') {
            return 'Kaladin';
        }
    });
});

$query = '{
    kaladin {
        name
    }
}';
(php)
class ScalarDate
{
    public $isResolver = true;

    protected $timestamp;

    public function __construct($timestamp)
    {
        $this->timestamp = $timestamp;
    }

    public function resolve()
    {
        return date('c', $this->timestamp);
    }
}
(bash)
composer