wappcode / gqlpdss
创建 GraphQL API 的实用工具
Requires
- php: >7.1
- doctrine/annotations: ^1.13
- doctrine/dbal: 3.1.4
- doctrine/orm: ^2.10.2
- ecodev/graphql-doctrine: ^7.1
- laminas/laminas-servicemanager: ^3.7
- nikic/fast-route: ^1.3
- symfony/cache: ^5.3
- symfony/yaml: 2.*
- wappcode/pdss-utilities: ^3.2
- webonyx/graphql-php: ^14.11
Requires (Dev)
This package is not auto-updated.
Last update: 2024-09-23 21:22:05 UTC
README
进入以下链接获取更多信息。 快速入门
安装
使用 Composer
执行
./composer.phar init
将库的引用添加到 composer.json 文件中
{
"name": "name/project",
"type": "project",
"require": {
"wappcode/gqlpdss": "^2.0.0"
},
}
执行
./composer.phar install
创建目录结构
config
data
modules
public
在 modules 文件夹中创建主模块 AppModule
创建以下目录结构
modules
AppModule
config
src
Entities
Graphql
Services
创建 modules/AppModule/src/Services/AppRouter.php 文件,内容如下
<?php
namespace AppModule\Services;
use GPDCore\Library\RouteModel;
use GPDCore\Library\AbstractRouter;
use GPDCore\Controllers\GraphqlController;
class AppRouter extends AbstractRouter
{
protected function addRoutes()
{
$GraphqlMethod = $this->isProductionMode ? 'POST' : ['POST','GET'];
// Agrega las entradas para consultas graphql
$this->addRoute(new RouteModel($GraphqlMethod, '/api', GraphqlController::class));
// Las demás rutas deben ir abajo para poder utilizar la configuración de los módulos y sus servicios
// entrada dominio principal
// ... otras rutas
}
}
添加 modules/AppModule/config/module.config.php 文件
<?php
return [];
添加 modules/AppModule/src/AppModule.php 文件
<?php
namespace AppModule;
use GPDCore\Library\AbstractModule;
use GraphQL\Type\Definition\Type;
class AppModule extends AbstractModule {
/**
* Array con la configuración del módulo
*
* @return array
*/
function getConfig(): array {
return require(__DIR__.'/../config/module.config.php');
}
function getServicesAndGQLTypes(): array
{
return [
'invokables' => [],
'factories'=> [],
'aliases' => []
];
}
/**
* Array con los resolvers del módulo
*
* @return array array(string $key => callable $resolver)
*/
function getResolvers(): array {
return [];
}
/**
* Array con los graphql Queries del módulo
*
* @return array
*/
function getQueryFields(): array {
return [
'echo' => [
'type' => Type::nonNull(Type::string()),
'args' => [
'message' => Type::nonNull(Type::string())
],
'resolve' => function($root, $args) { return $args["message"];}
],
];
}
/**
* Array con los graphql mutations del módulo
*
* @return array
*/
function getMutationFields(): array {
return [];
}
}
将以下代码添加到 composer.json 文件中
"autoload": {
"psr-4": {
"AppModule\\": "modules/AppModule/src/"
}
}
执行 ./composer.phar dump-autoload -o
创建一个用于覆盖模块配置的文件
config/local.config.php
<?php
return [];
创建 public/index.php 文件,内容如下
<?php
use AppModule\AppModule;
use AppModule\Services\AppRouter;
use GPDCore\Library\GPDApp;
use GPDCore\Services\ContextService;
use Laminas\ServiceManager\ServiceManager;
require_once __DIR__ . "/../vendor/autoload.php";
$enviroment = getenv("APP_ENV");
$serviceManager = new ServiceManager();
$context = new ContextService($serviceManager);
$router = new AppRouter();
$app = new GPDApp($context, $router, $enviroment);
$app->addModules([
AppModule::class,
]);
$localConfig = require __DIR__."/../config/local.config.php";
$context->getConfig()->add($localConfig);
$app->run();
添加 config/doctrine.entities.php 文件,内容如下
<?php
return [
"AppModule\Entities" => __DIR__."/../modules/AppModule/src/Entities",
];
添加 config/doctrine.local.php 文件,内容如下
<?php
return [
"driver"=> [
'user' => '',
'password' => '',
'dbname' => '',
'driver' => 'pdo_mysql',
'host' => '127.0.0.1',
'charset' => 'utf8mb4'
],
"entities"=> require __DIR__."/doctrine.entities.php"
];
创建 cli-config.php 文件,代码如下
<?php
use GPDCore\Factory\EntityManagerFactory;
use Doctrine\ORM\Tools\Console\ConsoleRunner;
require_once __DIR__."/vendor/autoload.php";
$options = require __DIR__."/config/doctrine.local.php";
$cacheDir = __DIR__ . "/data/DoctrineORMModule";
$entityManager = EntityManagerFactory::createInstance($options, $cacheDir, true, '');
return ConsoleRunner::createHelperSet($entityManager);
在 AppModule 中创建 entities
创建 modules/AppModule/src/Entities/Post.php 文件
<?php
declare(strict_types=1);
namespace GraphQLTests\Doctrine\Blog\Model;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use GPDCore\Entities\AbstractEntityModel;
/**
*
* @ORM\Entity
*
*/
final class Post extends AbstractEntityModel
{
const STATUS_PRIVATE = 'private';
const STATUS_PUBLIC = 'public';
/**
* @var string
*
* @ORM\Column(type="string", length=50, options={"default" = ""})
*/
private $title = '';
/**
* @var string
*
* @ORM\Column(type="text")
*/
private $body = '';
/**
* @var DateTimeImmutable
*
* @ORM\Column(type="datetime_immutable")
*/
private $publicationDate;
/**
* @var string
*
* @ORM\Column(type="string", options={"default" = Post::STATUS_PRIVATE})
*/
private $status = self::STATUS_PRIVATE;
/**
*
* @return string
*/
public function getTitle(): string
{
return $this->title;
}
/**
*
* @param string $title
*
* @return self
*/
public function setTitle(string $title)
{
$this->title = $title;
return $this;
}
/**
*
* @return string
*/
public function getBody(): string
{
return $this->body;
}
/**
*
* @param string $body
*
* @return self
*/
public function setBody(string $body)
{
$this->body = $body;
return $this;
}
/**
*
* @return DateTimeImmutable
*/
public function getPublicationDate(): DateTimeImmutable
{
return $this->publicationDate;
}
/**
*
* @param DateTimeImmutable $publicationDate
*
* @return self
*/
public function setPublicationDate(DateTimeImmutable $publicationDate)
{
$this->publicationDate = $publicationDate;
return $this;
}
/**
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
*
* @param string $status
*
* @return self
*/
public function setStatus(string $status)
{
$this->status = $status;
return $this;
}
}
更新 doctrine.entities.php 文件中的实体位置
return [
"AppModule\Entities" => __DIR__."/../modules/AppModule/src/Entities",
]
执行以下命令以生成更新数据库的 SQL 代码
./vendor/bin/doctrine orm:schema-tool:update --dump-sql
或执行以下命令以更新数据库
./vendor/bin/doctrine orm:schema-tool:update --force
注意:这些命令不应在生产环境中使用
使用命令启动
php -S localhost:8000 public/index.php
查询 GraphQL API 的路径为 https://:8000/api
API
ConnectionTypeFactory
生成列表查询分页的连接类型的类
方法
createConnectionType (\GraphQL\Type\Definition\ObjectType $type, string $name, string $description): \GraphQL\Type\Definition\ObjectType
创建具有以下字段的连接类型
{
totalCount: int!
pageInfo: PaginationInput {
hasPreviousPage: bool!
hasNextPage: bool!
startCursor: string!
endCursor: string!
},
edges: [EdgeType]! {
cursor: string!,
node: ObjectType!
}
}
createEdgeType(\GraphQL\Type\Definition\ObjectType $nodeType): \GraphQL\Type\Definition\ObjectType
创建 Edge 类型
{
cursor: string!,
node: ObjectType!
}