PHPackages                             moxuandi/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. moxuandi/yii2-graphql

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

moxuandi/yii2-graphql
=====================

facebook graphql server side for yii2 php framework

0.14.0(5y ago)178BSD-3-ClausePHPPHP &gt;=7.2.0

Since Jul 5Pushed 5y agoCompare

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

READMEChangelog (2)Dependencies (5)Versions (9)Used By (0)

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

[](#yii-graphql)

使用 Facebook [GraphQL](http://facebook.github.io/graphql/) 的PHP服务端实现. 扩展 [graphql-php](https://github.com/webonyx/graphql-php) 以适用于 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)

---

[Englist document](/README-en.md)

---

yii-graphql特点

- 配置简化,包括简化标准graphql协议的定义.
- 按需要\\懒加载,根据类型定义的全限定名,实现按需加载与懒,不需要在系统初始时将全部类型定义加载进入.
- mutation输入验证支持
- 提供控制器集成与授权支持

### 安装

[](#安装)

使用 [composer](https://getcomposer.org/) 安装:

```
composer require moxuandi/yii2-graphql

```

### Type

[](#type)

类型系统是GraphQL的核心,体现在GraphQLType中,通过解构graphql协议,并利用graph-php库达到细粒度的对所有元素的控制,方便根据自身需要进行类扩展.

GraphQLType的主要元素,\*\* 注意元素并不对应到属性或方法中(下同) \*\*

元素类型说明namestring**Required** 每一个类型都需要为其命名,如果能唯一是比较安全,但并不强制,该属性需要定义于attribute中fieldsarray**Required** 包含的字段内容,以fields()方法体现.resolveFieldcallback**function($value, $args, $context, GraphQL\\Type\\Definition\\ResolveInfo $info)** 对于字段的解释,比如fields定义user属性,则对应的解释方法为resolveUserField() ,$value指定为type定义的类型实例### Query

[](#query)

GraphQLQuery,GraphQLMutation继承了GraphQLField,元素结构是一致的,想做对于一些复用性的Field,可以继承它. Graphql的每次查询都需要对应到一个GraphQLQuery对象

GraphQLField的主要元素

元素类型说明typeObjectType对应的查询类型,单一类型用GraphQL::type指定,列表用Type::listOf(GraphQL::type)argsarray查询需要使用的参数,其中每个参数按照Field定义resolvecallback**function($value, $args, $context, GraphQL\\Type\\Definition\\ResolveInfo $info)**,$value为root数据,$args即查询参数,$context上下文,为Yii的yii\\web\\Application对象,$info为查询解析对象,一般在这个方法中处理根对象### Mutation

[](#mutation)

与GraphQLQuery是非常相像,参考说明.

### 简化处理

[](#简化处理)

简化了Field的声明,字段可直接使用type

```
// 标准方式
'id' => [
    'type'=>type::id(),
],
// 简化写法
'id'=>type::id()
```

### 在YII使用

[](#在yii使用)

本组件采用trait的方式在Component组件中被引入，组件宿主建议的方式是Module

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

Yii config file:

```
'components' => [
    'graphql'=>[
       'class'=>'xxx\xxxx\module',
       //主graphql协议配置
       'schema' => [
          'query' => [
              'user' => 'app\graphql\query\UsersQuery'
          ],
          'mutation' => [
              'login'
          ],
          //if you use sample query except query contain interface,fragment,not need set
          //the key must same as your class definded
          'types'=>[
              'Story'=>'yiiunit\extensions\graphql\objects\types\StoryType'
          ],
        ]
    ],
];
```

采用的是actions的方法进行集成

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

在采用动态解析的情况下,如果不想定义types时,schema的写法有讲究.可采用Type::class,避免采用Key方式,也方便直接通过IDE导航到对应的类下

```
'type' => GraphQL::type(UserType::class);
```

### 输入验证

[](#输入验证)

针对mutation的数据提交,提供了验证支持. 除了graphql基于的验证外,还可以使用yii的验证,目前为针对输入参数验证.直接在mutation定义中增加rules方法, 与Yii Model的使用方式是一致的.

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

### 授权验证

[](#授权验证)

由于graphql查询是可以采用组合方式，如一次查询合并了两个query，而这两个query具有不同的授权约束，因此在graph中需要采用自定义的验证方式。 我把这多次查询查询称为graphql actions;当所有的graphql actions条件都满足配置时，才通过授权检查。

#### 授权

[](#授权)

在controller的行为方法中设置采用的授权方法,例子如下，

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

如果要支持IntrospectionQueryr的授权，相应的graphql action为"\_\_schema"

### Demo

[](#demo)

#### 创建基于graphql协议的查询

[](#创建基于graphql协议的查询)

每次查询对应一个GraphQLQuery文件,

```
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use yii\graphql\base\GraphQLQuery;
use yii\graphql\GraphQL;

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']);
    }

}
```

根据查询协议定义类型文件

```
use GraphQL\Type\Definition\Type;
use yii\graphql\base\GraphQLType;
use yii\graphql\GraphQL;

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';
    }
}
```

#### 查询实例

[](#查询实例)

```
'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
            }
        }
    "
```

### 深入了解

[](#深入了解)

有必要了解一些graphql-php的相关知识,这部分git上的文档相对还少些,需要对源码的阅读.下面列出重点

#### DocumentNode (语法解构)

[](#documentnode-语法解构)

```
array definitions
    array OperationDefinitionNode
        string kind
        array NameNode
            string kind
            string value

```

### Future

[](#future)

- ActiveRecord generate tool for generating query and mutation class.
- 对于graphql的一些特殊语法,像参数语法,内置指令语法还未进行测试

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 86% 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 ~174 days

Recently: every ~267 days

Total

8

Last Release

2010d ago

PHP version history (2 changes)0.9PHP &gt;=5.6.0

0.13.8.1PHP &gt;=7.2.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/38183123fe75b8fbe91f8cde1a806d5fd9d0913edbbc53a1ae7d89c7907bbb9a?d=identicon)[moxuandi](/maintainers/moxuandi)

---

Top Contributors

[![tsingsun](https://avatars.githubusercontent.com/u/5848549?v=4)](https://github.com/tsingsun "tsingsun (43 commits)")[![moxuandi](https://avatars.githubusercontent.com/u/22020977?v=4)](https://github.com/moxuandi "moxuandi (6 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/moxuandi-yii2-graphql/health.svg)

```
[![Health](https://phpackages.com/badges/moxuandi-yii2-graphql/health.svg)](https://phpackages.com/packages/moxuandi-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)

PHPackages © 2026

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