{"id":15169504,"url":"https://github.com/tsingsun/yii2-graphql","last_synced_at":"2025-10-01T02:31:20.187Z","repository":{"id":57073224,"uuid":"78406868","full_name":"tsingsun/yii2-graphql","owner":"tsingsun","description":"facebook graphql server side for yii2 php framework","archived":true,"fork":false,"pushed_at":"2019-08-09T05:49:50.000Z","size":117,"stargazers_count":98,"open_issues_count":7,"forks_count":26,"subscribers_count":11,"default_branch":"master","last_synced_at":"2024-09-22T22:01:58.280Z","etag":null,"topics":["graphql","graphql-php","yii","yii-graphql"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tsingsun.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-01-09T08:01:04.000Z","updated_at":"2023-12-26T13:53:51.000Z","dependencies_parsed_at":"2022-08-24T14:54:39.939Z","dependency_job_id":null,"html_url":"https://github.com/tsingsun/yii2-graphql","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsingsun%2Fyii2-graphql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsingsun%2Fyii2-graphql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsingsun%2Fyii2-graphql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tsingsun%2Fyii2-graphql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tsingsun","download_url":"https://codeload.github.com/tsingsun/yii2-graphql/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":219875269,"owners_count":16554660,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql","graphql-php","yii","yii-graphql"],"created_at":"2024-09-27T07:02:46.156Z","updated_at":"2025-10-01T02:31:19.804Z","avatar_url":"https://github.com/tsingsun.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"yii-graphql\n==========\nUsing Facebook [GraphQL](http://facebook.github.io/graphql/) PHP server implementation. Extends [graphql-php](https://github.com/webonyx/graphql-php) to apply to YII2.\n\n[![Latest Stable Version](https://poser.pugx.org/tsingsun/yii2-graphql/v/stable.svg)](https://packagist.org/packages/tsingsun/yii2-graphql)\n[![Build Status](https://travis-ci.org/tsingsun/yii2-graphql.png?branch=master)](https://travis-ci.org/tsingsun/yii2-graphql)\n[![Total Downloads](https://poser.pugx.org/tsingsun/yii2-graphql/downloads.svg)](https://packagist.org/packages/tsingsun/yii2-graphql)\n\n--------\n\n[Chinese document](/docs/README-zh.md)\n\n-------\n\nFeatures\n\n* Configuration includes simplifying the definition of standard graphql protocols.\n* 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.\n* Mutation input validation support.\n* Provide controller integration and authorization support.\n\n### Install\n\nUsing [composer](https://getcomposer.org/)\n```\ncomposer require tsingsun/yii2-graphql\n```\n\n### Type\nThe 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\n\n\n#### The main elements of `GraphQLType`\n\nThe 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.\n\nElement  | Type | Description\n----- | ----- | -----\n`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.\n`description` | string | A description of the type and its use. The property needs to be defined in the `$attributes` property.\n`fields` | array | **Required** The included field content is represented by the fields () method.\n`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`.\n\n### Query\n\n`GraphQLQuery` and `GraphQLMutation` inherit `GraphQLField`. The element structure is consistent, and if you would like a reusable `Field`, you can inherit it.\nEach query of `Graphql` needs to correspond to a `GraphQLQuery` object\n\n#### The main elements of `GraphQLField`\n\n Element | Type  | Description\n----- | ----- | -----\n`type` | ObjectType | For the corresponding query type. The single type is specified by `GraphQL::type`, and a list by `Type::listOf(GraphQL::type)`.\n`args` | array | The available query parameters, each of which is defined by `Field`.\n`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.\n\n### Mutation\n\nDefinition is similar to `GraphQLQuery`, please refer to the above.\n\n### Simplified Field Definition\n\nSimplifies the declarations of `Field`, removing the need to defined as an array with the type key.\n\n#### Standard Definition\n\n```php\n//...\n'id' =\u003e [\n    'type' =\u003e Type::id(),\n],\n//...\n```\n\n#### Simplified Definition\n\n```php\n//...\n'id' =\u003e Type::id(),\n//...\n```\n\n### Yii Implementation\n\n### General configuration\n\nJsonParser configuration required\n\n```php\n'components' =\u003e [\n    'request' =\u003e [\n        'parsers' =\u003e [\n            'application/json' =\u003e 'yii\\web\\JsonParser',\n        ],\n    ],\n];\n```\n\n#### Module support\n\nCan easily be implemented with `yii\\graphql\\GraphQLModuleTrait`. The trait is responsible for initialization.\n\n```php\nclass MyModule extends \\yii\\base\\Module\n{\n    use \\yii\\graphql\\GraphQLModuleTrait;\n}\n```\n\nIn your application configuration file:\n\n```php\n'modules'=\u003e[\n    'moduleName ' =\u003e [\n        'class' =\u003e 'path\\to\\module'\n        //graphql config\n        'schema' =\u003e [\n            'query' =\u003e [\n                'user' =\u003e 'app\\graphql\\query\\UsersQuery'\n            ],\n            'mutation' =\u003e [\n                'login'\n            ],\n            // you do not need to set the types if your query contains interfaces or fragments\n            // the key must same as your defined class\n            'types' =\u003e [\n                'Story' =\u003e 'yiiunit\\extensions\\graphql\\objects\\types\\StoryType'\n            ],\n        ],\n    ],\n];\n```\n\nUse the controller to receive requests by using `yii\\graphql\\GraphQLAction`\n\n```php\nclass MyController extends Controller\n{\n   function actions() {\n       return [\n            'index'=\u003e[\n                'class'=\u003e'yii\\graphql\\GraphQLAction'\n            ],\n       ];\n   }\n}\n```\n\n#### Component Support\nalso you can include the trait with your own components,then initialization yourself.\n```php\n'components'=\u003e[\n    'componentsName' =\u003e [\n        'class' =\u003e 'path\\to\\components'\n        //graphql config\n        'schema' =\u003e [\n            'query' =\u003e [\n                'user' =\u003e 'app\\graphql\\query\\UsersQuery'\n            ],\n            'mutation' =\u003e [\n                'login'\n            ],\n            // you do not need to set the types if your query contains interfaces or fragments\n            // the key must same as your defined class\n            'types'=\u003e[\n                'Story'=\u003e'yiiunit\\extensions\\graphql\\objects\\types\\StoryType'\n            ],\n        ],\n    ],\n];\n```\n\n\n### Input validation\n\nValidation rules are supported.\nIn 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.\n\n```php\npublic function rules() {\n    return [\n        ['password','boolean']\n    ];\n}\n```\n\n### Authorization verification\n\nSince 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.\nI refer to this query as \"graphql actions\"; when all graphql actions conditions are configured, it passes the authorization check.\n\n#### Authenticate\n\nIn the behavior method of controller, the authorization method is set as follows\n\n```php\nfunction behaviors() {\n    return [\n        'authenticator'=\u003e[\n            'class' =\u003e 'yii\\graphql\\filter\\auth\\CompositeAuth',\n            'authMethods' =\u003e [\n                \\yii\\filters\\auth\\QueryParamAuth::className(),\n            ],\n            'except' =\u003e ['hello']\n        ],\n    ];\n}\n```\nIf you want to support IntrospectionQuery authorization, the corresponding graphql action is `__schema`\n\n#### Authorization\n\nIf the user has passed authentication, you may want to check the access for the resource. You can use `GraphqlAction`'s `checkAccess` method\nin the controller. It will check all graphql actions.\n\n```php\nclass GraphqlController extends Controller\n{\n    public function actions() {\n        return [\n            'index' =\u003e [\n                'class' =\u003e 'yii\\graphql\\GraphQLAction',\n                'checkAccess'=\u003e [$this,'checkAccess'],\n            ]\n        ];\n    }\n\n    /**\n     * authorization\n     * @param $actionName\n     * @throws yii\\web\\ForbiddenHttpException\n     */\n    public function checkAccess($actionName) {\n        $permissionName = $this-\u003emodule-\u003eid . '/' . $actionName;\n        $pass = Yii::$app-\u003egetAuthManager()-\u003echeckAccess(Yii::$app-\u003euser-\u003eid,$permissionName);\n        if (!$pass){\n            throw new yii\\web\\ForbiddenHttpException('Access Denied');\n        }\n    }\n}\n```\n\n### Demo\n\n#### Creating queries based on graphql protocols\n\nEach query corresponds to a GraphQLQuery file.\n\n```php\nclass UserQuery extends GraphQLQuery\n{\n    public function type() {\n        return GraphQL::type(UserType::class);\n    }\n\n    public function args() {\n        return [\n            'id'=\u003e[\n                'type' =\u003e Type::nonNull(Type::id())\n            ],\n        ];\n    }\n\n    public function resolve($value, $args, $context, ResolveInfo $info) {\n        return DataSource::findUser($args['id']);\n    }\n\n\n}\n```\n\nDefine type files based on query protocols\n\n```php\n\nclass UserType extends GraphQLType\n{\n    protected $attributes = [\n        'name'=\u003e'user',\n        'description'=\u003e'user is user'\n    ];\n\n    public function fields()\n    {\n        $result = [\n            'id' =\u003e ['type'=\u003eType::id()],\n            'email' =\u003e Types::email(),\n            'email2' =\u003e Types::email(),\n            'photo' =\u003e [\n                'type' =\u003e GraphQL::type(ImageType::class),\n                'description' =\u003e 'User photo URL',\n                'args' =\u003e [\n                    'size' =\u003e Type::nonNull(GraphQL::type(ImageSizeEnumType::class)),\n                ]\n            ],\n            'firstName' =\u003e [\n                'type' =\u003e Type::string(),\n            ],\n            'lastName' =\u003e [\n                'type' =\u003e Type::string(),\n            ],\n            'lastStoryPosted' =\u003e GraphQL::type(StoryType::class),\n            'fieldWithError' =\u003e [\n                'type' =\u003e Type::string(),\n                'resolve' =\u003e function() {\n                    throw new \\Exception(\"This is error field\");\n                }\n            ]\n        ];\n        return $result;\n    }\n\n    public function resolvePhotoField(User $user,$args){\n        return DataSource::getUserPhoto($user-\u003eid, $args['size']);\n    }\n\n    public function resolveIdField(User $user, $args)\n    {\n        return $user-\u003eid.'test';\n    }\n\n    public function resolveEmail2Field(User $user, $args)\n    {\n        return $user-\u003eemail2.'test';\n    }\n\n\n}\n```\n\n#### Query instance\n\n```php\n'hello' =\u003e  \"\n        query hello{hello}\n    \",\n\n    'singleObject' =\u003e  \"\n        query user {\n            user(id:\\\"2\\\") {\n                id\n                email\n                email2\n                photo(size:ICON){\n                    id\n                    url\n                }\n                firstName\n                lastName\n\n            }\n        }\n    \",\n    'multiObject' =\u003e  \"\n        query multiObject {\n            user(id: \\\"2\\\") {\n                id\n                email\n                photo(size:ICON){\n                    id\n                    url\n                }\n            }\n            stories(after: \\\"1\\\") {\n                id\n                author{\n                    id\n                }\n                body\n            }\n        }\n    \",\n    'updateObject' =\u003e  \"\n        mutation updateUserPwd{\n            updateUserPwd(id: \\\"1001\\\", password: \\\"123456\\\") {\n                id,\n                username\n            }\n        }\n    \"\n```\n\n### Exception Handling\n\nYou can config the error formater for graph. The default handle uses `yii\\graphql\\ErrorFormatter`,\nwhich optimizes the processing of Model validation results.\n\n```php\n'modules'=\u003e[\n    'moduleName' =\u003e [\n       'class' =\u003e 'path\\to\\module'\n       'errorFormatter' =\u003e ['yii\\graphql\\ErrorFormatter', 'formatError'],\n    ],\n];\n```\n\n### Future\n\n* `ActiveRecord` tool for generating query and mutation class.\n* Some of the special syntax for graphql, such as `@Directives`, has not been tested\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftsingsun%2Fyii2-graphql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftsingsun%2Fyii2-graphql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftsingsun%2Fyii2-graphql/lists"}