youshido / api-images
用于实现图像到GraphQL API的库
v2.0.6
2017-03-06 04:10 UTC
Requires
- php: >=7.0.0
- imagine/imagine: ^0.6.3
README
Symfony 插件,用于简化图像在GraphQL API中的实现(包含GraphQL实现及其文档,可在此处找到:https://github.com/Youshido/GraphQLBundle)。插件提供 UploadImageMutation
mutation { uploadImage(field: "image") { id url resized(width: 100, height: 100, mode: INSET) { url } } }
变更默认请求内容类型为 multipart/form-data
并在传入的参数字段 field
中包含图像数据。此外,插件还提供 ImageField
以便在API中使用,如下所示
{ me { id firstName lastName image { // image field from bundle url resized(width: 100, height: 100, mode: INSET) { url } } } }
或者,您可以直接将参数添加到图像字段,以便更方便地使用。
{ me { id firstName lastName small: image(width: 100, height: 100, mode: INSET) { // resized directly url } medium: image(width: 500, height: 300, mode: OUTBOUND) { // different mode url } fullSize: image { url } } }
如何使用
1. 安装
composer require youshido/api-images
2. 配置
2.1 在 AppKernel.php
中启用插件
$bundles[] = new Youshido\ImagesBundle\ImagesBundle()
2.2 在 routing.yml
中添加新路由
images: resource: "@ImagesBundle/Controller/" type: annotation
2.3 在 config.yml
中配置插件
images: web_root: "%kernel.root_dir%/../web" #your app web root path_prefix: "uploads/images" #folder in web root where images will be stored platform: orm #orm or odm driver: gd #imagine driver, can be gd, imagick or gmagick
3. 设置实体
3.1 ORM 设置
添加图像属性并实现 ImageableInterface
到您的实体
<?php use Youshido\ImagesBundle\Entity\Interfaces\ImageableInterface; /** * @ORM\Entity */ class YourEntity implements ImageableInterface { // other your properties /** * @var Image * * @ORM\ManyToOne(targetEntity="Youshido\ImagesBundle\Entity\Image") */ private $image; /** * @return Image */ public function getImage() { return $this->image; } /** * @param Image $image * * @return User */ public function setImage(Image $image = null) { $this->image = $image; return $this; }
3.2 ODM 设置
使用 ImageableTrait
并实现 ImageableInterface
到您的实体
<?php use Youshido\ImagesBundle\Document\Interfaces\ImageableInterface; use Youshido\ImagesBundle\Document\Traits\ImageableTrait; /** * @MongoDB\Document() */ class Category implements ImageableInterface { use ImageableTrait; //other properties
4. 设置 GraphQL 模式
4.1 将 UploadImageMutation
添加到您的 MutationType
<?php use Youshido\ImagesBundle\GraphQL\Field\Mutation\UploadImageField; class MutationType extends AbstractObjectType { public function build($config) { $config->addFields([ new UploadImageField(), // other mutations ]); } }
4.2 将图像字段添加到您的类型
use Youshido\ImagesBundle\GraphQL\Field\Query\ImageField; class CategoryType extends AbstractObjectType { public function build($config) { $config->addFields([ // category fields new ImageField() ]); } }
4.3 在字段解析器中设置/更新图像
//for odm $image = $dm->getRepository(Image::class)->find($imageId); $yourEntity->setImage($image ? new EmbeddedImage($image) : null); //for orm $image = $em->getRepository(Image::class)->find($imageId); $yourEntity->setImage($image);