PHP code example of plato-solutions / yii2-graphql
1. Go to this page and download the library: Download plato-solutions/yii2-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/ */
namespace backend\modules\graphql;
use yii\base\Module;
use yii\graphql\GraphQLModuleTrait;
class GraphqlModule extends Module{
use GraphQLModuleTrait;
}
namespace backend\modules\graphql\controllers;
use Yii;
use yii\rest\Controller;
class DefaultController extends Controller
{
public function actions()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'index' => [
'class' => 'yii\graphql\GraphQLAction'
],
];
}
}
/**
* This is the model class for table "country".
*
* @property string $code
* @property string $name
* @property int $population
* @property Person $leader
*/
class Country extends \yii\db\ActiveRecord
{
namespace backend\modules\graphql\types;
use GraphQL\Type\Definition\Type;
use yii\graphql\base\GraphQLType;
use yii\graphql\GraphQL;
class CountryType extends GraphQLType
{
protected $attributes = [
'name' => 'country',
'description' => 'description here'
];
public function fields()
{
return [
'id' => Type::id(),
'name' => Type::string(),
'population' => Type::int(),
'leader' => GraphQLType::type(PersonType::class)
];
}
}
namespace backend\modules\graphql\queries;
use GraphQL\Type\Definition\Type;
use yii\graphql\queries\ModelQuery;
use backend\modules\graphql\types\CountryType;
use backend\models\Country;
class CountryQuery extends ModelQuery
{
public $type = CountryType::class;
public $model = Country::class;
public function args()
{
return [
'id' => Type::id(),
'name' => Type::string(),
'population' => Type::int(),
'leaderId' => Type::id()
];
// replace the non-scalar type with it's id in the args
}
}
return [
'query' => [
'country' => 'backend\modules\graphql\queries\CountryQuery',
//... add all your queries here
],
'mutation' => [
//... add all your mutations here
],
'types' => [
'country' => 'backend\modules\graphql\types\CountryType',
//... add all your types here
]
];