ozznest / 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实现和文档的扩展包在此处)。扩展包提供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);