ozznest/base-graphql-bundle

Symfony GraphQl Bundle

1.0.2 2024-02-11 13:58 UTC

This package is auto-updated.

Last update: 2024-09-11 15:13:56 UTC


README

这是一个基于纯 PHP GraphQL Server 实现的包

本包提供给您

  • 完全兼容 GraphQL RFC 规范
  • 敏捷的对象导向结构,以构建您的 GraphQL Schema
  • 直观的类型系统,让您能够更快地构建项目并保持一致性
  • 内置对您开发的 GraphQL Schema 的验证
  • 丰富的示例文档类
  • 自动创建端点 /graphql 来处理请求

有简单的演示应用程序来展示我们如何构建我们的 API,请参阅 GraphQLDemoApp

目录

安装

我们假设您已经安装了 composer,如果没有,请从 官方网站 安装。
如果您需要安装 Symfony 框架的帮助,请点击此链接 https://symfony.ac.cn/doc/current/book/installation.html

安装 Symfony 的快捷方式:composer create-project symfony/framework-standard-edition my_project_name

一旦您启动了 composer,就可以安装 GraphQL Bundle。
转到您的项目文件夹并运行

composer require youshido/graphql-bundle

然后,在您的 app/AppKernel.php 文件中启用该包

new Youshido\GraphQLBundle\GraphQLBundle(),

将路由引用添加到 app/config/routing.yml

graphql:
    resource: "@GraphQLBundle/Controller/"

或者

graphql:
    resource: "@GraphQLBundle/Resources/config/route.xml"

如果您还没有配置网络服务器,可以使用捆绑版本,只需运行 php bin/console server:run

让我们检查您是否已经正确完成了一切——尝试访问网址 localhost:8000/graphql
您应该会得到以下错误的 JSON 响应

{"errors":[{"message":"Schema class does not exist"}]}

这是因为处理器还没有指定 GraphQL Schema。您需要创建一个 GraphQL Schema 类并将其设置在您的 app/config/config.yml 文件中。

有一种使用内联方法而不创建 Schema 类的方法,为了这样做,您必须定义自己的 GraphQL 控制器并使用处理器的 ->setSchema 方法来设置 Schema。

创建 Schema 类最快的方法是使用本包附带的生成器

php bin/console graphql:configure AppBundle

在这里 AppBundle 是类将被生成的包的名称。
您将被要求确认创建类。

添加配置文件中的参数后,在浏览器中尝试访问以下链接 - http://localhost:8000/graphql?query={hello(name:World)}

或者,您可以在控制台中使用 CURL 客户端执行相同的请求
curl http://localhost:8000/graphql --data "query={ hello(name: \"World\") }"

测试 Schema 的成功响应将显示

{"data":{"hello":"world!"}}

这意味着您已为 Symfony 框架配置了 GraphQL Bundle,现在可以构建您的 GraphQL Schema

下一步是执行以下操作来为 GraphiQL 探索器链接资产

php bin/console assets:install --symlink

现在您可以通过 http://localhost:8000/graphql/explorer 访问它

Symfony 特性

Class AbstractContainerAwareField

AbstractContainerAwareField 类用于自动将容器传递给字段,添加了在解析函数中使用容器的能力

class RootDirField extends AbstractContainerAwareField
{

    /**
     * @inheritdoc
     */
    public function getType()
    {
        return new StringType();
    }

    /**
     * @inheritdoc
     */
    public function resolve($value, array $args, ResolveInfo $info)
    {
        return $this->container->getParameter('kernel.root_dir');
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'rootDir';
    }

将服务方法作为可调用对象

支持将服务方法作为可调用的resolve

$config->addField(new Field([
    'name'    => 'cacheDir',
    'type'    => new StringType(),
    'resolve' => ['@resolve_service', 'getCacheDir']
]))

事件

您可以使用Symfony事件调度器来控制在解析GraphQL查询时发生的特定事件。

namespace ...\...\..;

use Youshido\GraphQL\Event\ResolveEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MyGraphQLResolveEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            'graphql.pre_resolve'  => 'onPreResolve',
            'graphql.post_resolve' => 'onPostResolve'
        ];
    }

    public function onPreResolve(ResolveEvent $event)
    {
		//$event->getFields / $event->getAstFields()..
    }

    public function onPostResolve(ResolveEvent $event)
    {
		//$event->getFields / $event->getAstFields()..
    }
}

配置

现在配置您的订阅者,以便捕获事件。在Symfony中,这可以通过XML、Yaml或PHP来实现。

<service id="my_own_bundle.event_subscriber.my_graphql_resolve_event_subscriber" class="...\...\...\MyGraphQLResolveEventSubscriber">
	<tag name="graphql.event_subscriber" />
</service>

安全

此Bundle提供了两种保护您应用程序的方法:使用黑/白操作列表或使用安全投票者。

黑/白列表

用于保护一些根操作。要启用它,您需要在您的config.yml文件中写入以下内容

graphql:

  #...

  security:
    black_list: ['hello'] # or white_list: ['hello']

使用安全投票者

用于保护任何字段解析,并支持两种类型的保护:根操作和任何其他字段解析(包括内部字段、标量类型字段、根操作)。要使用您指定的逻辑保护根操作,您需要在配置中启用它,并使用SecurityManagerInterface::RESOLVE_ROOT_OPERATION_ATTRIBUTE属性。同样,要启用字段保护,也需要进行相同的操作,但在这种情况下,使用SecurityManagerInterface::RESOLVE_FIELD_ATTRIBUTE属性。有关投票者的官方文档点击这里

注意:启用字段安全将导致性能显著下降

配置示例

graphql:
    security:
        guard:
            field: true # for any field security
            operation: true # for root level security

投票示例(添加到您的services.yml文件中,带有标签security.voter

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQLBundle\Security\Manager\SecurityManagerInterface;

class GraphQLVoter extends Voter
{

    /**
     * @inheritdoc
     */
    protected function supports($attribute, $subject)
    {
        return in_array($attribute, [SecurityManagerInterface::RESOLVE_FIELD_ATTRIBUTE, SecurityManagerInterface::RESOLVE_ROOT_OPERATION_ATTRIBUTE]);
    }

    /**
     * @inheritdoc
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        // your own validation logic here

        if (SecurityManagerInterface::RESOLVE_FIELD_ATTRIBUTE == $attribute) {
            /** @var $subject ResolveInfo */
            if ($subject->getField()->getName() == 'hello') {
                return false;
            }

            return true;
        } elseif (SecurityManagerInterface::RESOLVE_ROOT_OPERATION_ATTRIBUTE == $attribute) {
            /** @var $subject Query */
            if ($subject->getName() == '__schema') {
                return true;
            }
        }
    }
}

GraphiQL扩展

要运行graphiql扩展,只需尝试访问http://your_domain/graphql/explorer

文档

所有详细文档可在主GraphQL仓库中找到—— http://github.com/youshido/graphql/