PHPackages                             virtualwonders/yii2-graphql - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. virtualwonders/yii2-graphql

ActiveYii2-extension[API Development](/categories/api)

virtualwonders/yii2-graphql
===========================

facebook graphql server side for yii2 php framework

0.11.5(6y ago)0595BSD-3-ClausePHPPHP &gt;=5.6.0

Since Jul 5Pushed 6y agoCompare

[ Source](https://github.com/virtualwonders/yii2-graphql)[ Packagist](https://packagist.org/packages/virtualwonders/yii2-graphql)[ RSS](/packages/virtualwonders-yii2-graphql/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (5)Versions (8)Used By (0)

yii-graphql
===========

[](#yii-graphql)

Using Facebook [GraphQL](http://facebook.github.io/graphql/) PHP server implementation. Extends [graphql-php](https://github.com/webonyx/graphql-php) to apply to YII2.

[![Latest Stable Version](https://camo.githubusercontent.com/5e63fab36ae69d3da3dd112dae72934a97a972e40a509b075bf24a4162da4bb3/68747470733a2f2f706f7365722e707567782e6f72672f7473696e6773756e2f796969322d6772617068716c2f762f737461626c652e737667)](https://packagist.org/packages/tsingsun/yii2-graphql)[![Build Status](https://camo.githubusercontent.com/edf52fb42d0dcd18844fc066190da05c6929aaabfc823602ed054a98721ad0b5/68747470733a2f2f7472617669732d63692e6f72672f7473696e6773756e2f796969322d6772617068716c2e706e673f6272616e63683d6d6173746572)](https://travis-ci.org/tsingsun/yii2-graphql)[![Total Downloads](https://camo.githubusercontent.com/4ec7ef3f0a293a9ef462debfab239f496e32a151e521bf8dc9fa2b544e97c372/68747470733a2f2f706f7365722e707567782e6f72672f7473696e6773756e2f796969322d6772617068716c2f646f776e6c6f6164732e737667)](https://packagist.org/packages/tsingsun/yii2-graphql)

---

[Chinese document](/docs/README-zh.md)

---

Features

- Configuration includes simplifying the definition of standard graphql protocols.
- Based on the full name defined by the type, implementing on-demand loading and lazy loading, and no need to define all type definitions into the system at load.
- Mutation input validation support.
- Provide controller integration and authorization support.

### Install

[](#install)

Using [composer](https://getcomposer.org/)

```
composer require tsingsun/yii2-graphql

```

### Type

[](#type)

The type system is the core of GraphQL, which is embodied in `GraphQLType`. By deconstructing the GraphQL protocol and using the [graph-php](https://github.com/webonyx/graphql-php) library to achieve fine-grained control of all elements, it is convenient to extend the class according to its own needs

#### The main elements of `GraphQLType`

[](#the-main-elements-of-graphqltype)

The following elements can be declared in the `$attributes` property of the class, or as a method, unless stated otherwise. This also applies to all elements after this.

ElementTypeDescription`name`string**Required** Each type needs to be named, with unique names preferred to resolve potential conflicts. The property needs to be defined in the `$attributes` property.`description`stringA description of the type and its use. The property needs to be defined in the `$attributes` property.`fields`array**Required** The included field content is represented by the fields () method.`resolveField`callback**function($value, $args, $context, GraphQL\\Type\\Definition\\ResolveInfo $info)** For the interpretation of a field. For example: the fields definition of the user property, the corresponding method is `resolveUserField()`, and `$value` is the passed type instance defined by `type`.### Query

[](#query)

`GraphQLQuery` and `GraphQLMutation` inherit `GraphQLField`. The element structure is consistent, and if you would like a reusable `Field`, you can inherit it. Each query of `Graphql` needs to correspond to a `GraphQLQuery` object

#### The main elements of `GraphQLField`

[](#the-main-elements-of-graphqlfield)

ElementTypeDescription`type`ObjectTypeFor the corresponding query type. The single type is specified by `GraphQL::type`, and a list by `Type::listOf(GraphQL::type)`.`args`arrayThe available query parameters, each of which is defined by `Field`.`resolve`callback**function($value, $args, $context, GraphQL\\Type\\Definition\\ResolveInfo $info)** `$value` is the root data, `$args` is the query parameters, `$context` is the `yii\web\Application` object, and `$info` resolves the object for the query. The root object is handled in this method.### Mutation

[](#mutation)

Definition is similar to `GraphQLQuery`, please refer to the above.

### Simplified Field Definition

[](#simplified-field-definition)

Simplifies the declarations of `Field`, removing the need to defined as an array with the type key.

#### Standard Definition

[](#standard-definition)

```
//...
'id' => [
    'type' => Type::id(),
],
//...
```

#### Simplified Definition

[](#simplified-definition)

```
//...
'id' => Type::id(),
//...
```

### Yii Implementation

[](#yii-implementation)

### General configuration

[](#general-configuration)

JsonParser configuration required

```
'components' => [
    'request' => [
        'parsers' => [
            'application/json' => 'yii\web\JsonParser',
        ],
    ],
];
```

#### Module support

[](#module-support)

Can easily be implemented with `yii\graphql\GraphQLModuleTrait`. The trait is responsible for initialization.

```
class MyModule extends \yii\base\Module
{
    use \yii\graphql\GraphQLModuleTrait;
}
```

In your application configuration file:

```
'modules'=>[
    'moduleName ' => [
        'class' => 'path\to\module'
        //graphql config
        'schema' => [
            'query' => [
                'user' => 'app\graphql\query\UsersQuery'
            ],
            'mutation' => [
                'login'
            ],
            // you do not need to set the types if your query contains interfaces or fragments
            // the key must same as your defined class
            'types' => [
                'Story' => 'yiiunit\extensions\graphql\objects\types\StoryType'
            ],
        ],
    ],
];
```

Use the controller to receive requests by using `yii\graphql\GraphQLAction`

```
class MyController extends Controller
{
   function actions() {
       return [
            'index'=>[
                'class'=>'yii\graphql\GraphQLAction'
            ],
       ];
   }
}
```

#### Component Support

[](#component-support)

also you can include the trait with your own components,then initialization yourself.

```
'components'=>[
    'componentsName' => [
        'class' => 'path\to\components'
        //graphql config
        'schema' => [
            'query' => [
                'user' => 'app\graphql\query\UsersQuery'
            ],
            'mutation' => [
                'login'
            ],
            // you do not need to set the types if your query contains interfaces or fragments
            // the key must same as your defined class
            'types'=>[
                'Story'=>'yiiunit\extensions\graphql\objects\types\StoryType'
            ],
        ],
    ],
];
```

### Input validation

[](#input-validation)

Validation rules are supported. In addition to graphql based validation, you can also use Yii Model validation, which is currently used for the validation of input parameters. The rules method is added directly to the mutation definition.

```
public function rules() {
    return [
        ['password','boolean']
    ];
}
```

### Authorization verification

[](#authorization-verification)

Since graphql queries can be combined, such as when a query merges two query, and the two query have different authorization constraints, custom authentication is required. I refer to this query as "graphql actions"; when all graphql actions conditions are configured, it passes the authorization check.

#### Authenticate

[](#authenticate)

In the behavior method of controller, the authorization method is set as follows

```
function behaviors() {
    return [
        'authenticator'=>[
            'class' => 'yii\graphql\filter\auth\CompositeAuth',
            'authMethods' => [
                \yii\filters\auth\QueryParamAuth::className(),
            ],
            'except' => ['hello']
        ],
    ];
}
```

If you want to support IntrospectionQuery authorization, the corresponding graphql action is `__schema`

#### Authorization

[](#authorization)

If the user has passed authentication, you may want to check the access for the resource. You can use `GraphqlAction`'s `checkAccess` method in the controller. It will check all graphql actions.

```
class GraphqlController extends Controller
{
    public function actions() {
        return [
            'index' => [
                'class' => 'yii\graphql\GraphQLAction',
                'checkAccess'=> [$this,'checkAccess'],
            ]
        ];
    }

    /**
     * authorization
     * @param $actionName
     * @throws yii\web\ForbiddenHttpException
     */
    public function checkAccess($actionName) {
        $permissionName = $this->module->id . '/' . $actionName;
        $pass = Yii::$app->getAuthManager()->checkAccess(Yii::$app->user->id,$permissionName);
        if (!$pass){
            throw new yii\web\ForbiddenHttpException('Access Denied');
        }
    }
}
```

### Demo

[](#demo)

#### Creating queries based on graphql protocols

[](#creating-queries-based-on-graphql-protocols)

Each query corresponds to a GraphQLQuery file.

```
class UserQuery extends GraphQLQuery
{
    public function type() {
        return GraphQL::type(UserType::class);
    }

    public function args() {
        return [
            'id'=>[
                'type' => Type::nonNull(Type::id())
            ],
        ];
    }

    public function resolve($value, $args, $context, ResolveInfo $info) {
        return DataSource::findUser($args['id']);
    }

}
```

Define type files based on query protocols

```
class UserType extends GraphQLType
{
    protected $attributes = [
        'name'=>'user',
        'description'=>'user is user'
    ];

    public function fields()
    {
        $result = [
            'id' => ['type'=>Type::id()],
            'email' => Types::email(),
            'email2' => Types::email(),
            'photo' => [
                'type' => GraphQL::type(ImageType::class),
                'description' => 'User photo URL',
                'args' => [
                    'size' => Type::nonNull(GraphQL::type(ImageSizeEnumType::class)),
                ]
            ],
            'firstName' => [
                'type' => Type::string(),
            ],
            'lastName' => [
                'type' => Type::string(),
            ],
            'lastStoryPosted' => GraphQL::type(StoryType::class),
            'fieldWithError' => [
                'type' => Type::string(),
                'resolve' => function() {
                    throw new \Exception("This is error field");
                }
            ]
        ];
        return $result;
    }

    public function resolvePhotoField(User $user,$args){
        return DataSource::getUserPhoto($user->id, $args['size']);
    }

    public function resolveIdField(User $user, $args)
    {
        return $user->id.'test';
    }

    public function resolveEmail2Field(User $user, $args)
    {
        return $user->email2.'test';
    }

}
```

#### Query instance

[](#query-instance)

```
'hello' =>  "
        query hello{hello}
    ",

    'singleObject' =>  "
        query user {
            user(id:\"2\") {
                id
                email
                email2
                photo(size:ICON){
                    id
                    url
                }
                firstName
                lastName

            }
        }
    ",
    'multiObject' =>  "
        query multiObject {
            user(id: \"2\") {
                id
                email
                photo(size:ICON){
                    id
                    url
                }
            }
            stories(after: \"1\") {
                id
                author{
                    id
                }
                body
            }
        }
    ",
    'updateObject' =>  "
        mutation updateUserPwd{
            updateUserPwd(id: \"1001\", password: \"123456\") {
                id,
                username
            }
        }
    "
```

### Exception Handling

[](#exception-handling)

You can config the error formater for graph. The default handle uses `yii\graphql\ErrorFormatter`, which optimizes the processing of Model validation results.

```
'modules'=>[
    'moduleName' => [
       'class' => 'path\to\module'
       'errorFormatter' => ['yii\graphql\ErrorFormatter', 'formatError'],
    ],
];
```

### Future

[](#future)

- `ActiveRecord` tool for generating query and mutation class.
- Some of the special syntax for graphql, such as `@Directives`, has not been tested

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 97.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~169 days

Recently: every ~215 days

Total

7

Last Release

2218d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a7010e1753ada316fac42605142206d81f211ec82957723cb98244514883b432?d=identicon)[virtualwonders](/maintainers/virtualwonders)

---

Top Contributors

[![tsingsun](https://avatars.githubusercontent.com/u/5848549?v=4)](https://github.com/tsingsun "tsingsun (43 commits)")[![TerraSkye](https://avatars.githubusercontent.com/u/5426161?v=4)](https://github.com/TerraSkye "TerraSkye (1 commits)")

---

Tags

graphqlyii2

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/virtualwonders-yii2-graphql/health.svg)

```
[![Health](https://phpackages.com/badges/virtualwonders-yii2-graphql/health.svg)](https://phpackages.com/packages/virtualwonders-yii2-graphql)
```

###  Alternatives

[aimeos/ai-admin-graphql

Aimeos Admin GraphQL API extension

944100.0k4](/packages/aimeos-ai-admin-graphql)[oxid-esales/graphql-base

OXID eSales GraphQL base module

24101.0k10](/packages/oxid-esales-graphql-base)[rubix/server

Deploy your Rubix ML models to production with scalable stand-alone inference servers.

632.3k](/packages/rubix-server)[apexwire/yii2-restclient

Tools to use API as ActiveRecord for Yii2

143.5k](/packages/apexwire-yii2-restclient)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
