PHPackages                             maxxxam/graphql-yii - 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. maxxxam/graphql-yii

ActiveLibrary[API Development](/categories/api)

maxxxam/graphql-yii
===================

GraphQL, yii2 lib

v0.2.1(9y ago)132692MITPHPPHP &gt;=5.5.9

Since Oct 4Pushed 1y ago3 watchersCompare

[ Source](https://github.com/MaxXxaM/graphql-yii)[ Packagist](https://packagist.org/packages/maxxxam/graphql-yii)[ RSS](/packages/maxxxam-graphql-yii/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (2)Versions (9)Used By (0)

Yii2 GraphQL
============

[](#yii2-graphql)

Данное расширение позволяет реализовать GraphQL API в Yii2. Расширение основано на [расширении GraphQL webonyx](https://github.com/webonyx/graphql-php). Более подробная информация о GraphQL - [GraphQL Introduction](http://facebook.github.io/react/blog/2015/05/01/graphql-introduction.html).

Установка
---------

[](#установка)

#### Зависимости:

[](#зависимости)

- [Базовое расширение GraphQL PHP](https://github.com/webonyx/graphql-php)
- [Filsh/yii2-oauth2-server](https://github.com/Filsh/yii2-oauth2-server)

**1-** Установка пакета через Composer. Добавьте следующий код в файл `composer.json`.

```
{
	"require": {
		"maxxxam/graphql": "~0.2"
	}
}
```

**2-** Запустите установку пакетов Composer

```
$ composer install
```

или обновите вместе с существующими пакетами

```
$ composer update
```

### Yii2

[](#yii2)

**1-** Добавьте компонент в `config/main.php` file

```
'graphql' => [
    'graphql' => require(__DIR__ . DIRECTORY_SEPARATOR . 'require' . DIRECTORY_SEPARATOR . 'graphql.php')
],
```

**2-** Переместите config `./src/config/require` в `common/config/require`. Отредактируйте конфигурацию согласно вашему окружению. Объекты Types, Queries, Mutations могут быть загружены вручную (заданием в конфигурации), либо автоматически из заданных директорий. Пример конфигурации `graphql.php` приведен ниже:

```
$appNamespace = 'app\modules\graphql';
$graphqlDir = dirname(dirname(__DIR__)) . '/modules/graphql';

return [
    'class' => 'GraphQLYii\GraphQL',
    'namespace' => $appNamespace,
    'graphqlDir' => $graphqlDir,
    'types' => [
        'UserType' => $appNamespace . '\types\UserType',
        'AccessType' => $appNamespace . '\types\AccessType',
        'ImageType' => $appNamespace . '\types\ImageType',
        'EventType' => $appNamespace . '\types\EventType',
        'TrophyType' => $appNamespace . '\types\TrophyType',
        'TeamType' => $appNamespace . '\types\TeamType',
        'AlbumType' => $appNamespace . '\types\AlbumType',
        'FriendType' => $appNamespace . '\types\FriendType',
        'SportType' => $appNamespace . '\types\SportType',
    ],
    'queries' => [
        'UsersQuery' => $appNamespace . '\query\user\UsersQuery',
        'UserQuery' => $appNamespace . '\query\user\UserQuery'
    ],
    'mutations' => [
        'AddFriendMutation' => $appNamespace . '\mutation\user\AddFriendMutation',
        'RemoveFriendMutation' => $appNamespace . '\mutation\user\RemoveFriendMutation',
        'SignupMutation' => $appNamespace . '\mutation\user\SignupMutation',
    ],
    'typesPath' => '/types',
    'queriesPath' => '/queries',
    'mutationsPath' => '/mutations',
    'subscriptionPath' => '/subscription',
];
```

**3-** Создайте новый action для обработки пользовательского запроса

```
public function actionIndex(){
    Yii::$app->response->format = Response::FORMAT_JSON;

    $data = Yii::$app->request->post();

    $query = isset($data['query']) ? str_replace(["\r","\n"], "", $data['query']) : null;
    $params = isset($data['variables']) ? str_replace(["\r","\n"], "", $data['variables']) : null;

    /** @var GraphQL $GraphQL */
    $GraphQL = \Yii::$app->get('graphql');

    $result = $GraphQL->query($query, $params);

    if (!empty($result['errors'])){
        Yii::$app->response->setStatusCode(400);
    }

    Yii::$app->response->headers->add('Content-Length', strlen(json_encode($result)));
    Yii::$app->response->headers->add('Content-Type', 'application/json');

    $stream = fopen('php://memory','wb');
    fwrite($stream, json_encode($result));
    rewind($stream);

    Yii::$app->response->stream = $stream;
    Yii::$app->response->send();

    return true;

}
```

**4-** В качестве авторизации используется oAuth2 сервер [Filsh/yii2-oauth2-server](https://github.com/Filsh/yii2-oauth2-server)

**5-** Добавьте поведение в Controller

```
public function behaviors()
{
    Yii::$app->controller->enableCsrfValidation = false;
    return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                ['class' => HttpBearerAuth::className()],
                ['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
            ]
        ],
        'exceptionFilter' => [
            'class' => ErrorToExceptionFilter::className()
        ],
    ]);
}
```

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

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 ~35 days

Recently: every ~21 days

Total

7

Last Release

3297d ago

PHP version history (2 changes)v0.1PHP &gt;=5.3.3

v0.2PHP &gt;=5.5.9

### Community

Maintainers

![](https://www.gravatar.com/avatar/0aff407c77b81b365828415460c6ece8d2590bd6e630a566c3aba18b1880817b?d=identicon)[MaxXxaM](/maintainers/MaxXxaM)

---

Tags

graphqlyii2

### Embed Badge

![Health badge](/badges/maxxxam-graphql-yii/health.svg)

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

###  Alternatives

[nuwave/lighthouse

A framework for serving GraphQL from Laravel

3.5k10.7M93](/packages/nuwave-lighthouse)[aimeos/ai-admin-graphql

Aimeos Admin GraphQL API extension

944100.0k4](/packages/aimeos-ai-admin-graphql)[mll-lab/laravel-graphiql

Easily integrate GraphiQL into your Laravel project

683.2M9](/packages/mll-lab-laravel-graphiql)[scrnhq/laravel-bakery

An on-the-fly GraphQL Schema generator from Eloquent models for Laravel.

10518.2k](/packages/scrnhq-laravel-bakery)[worksome/graphlint

A static analysis tool for GraphQL

13189.4k](/packages/worksome-graphlint)[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)
