Graphql和RestApi一样,是访问接口的一种方式,具体在magento2中的不同之处主要是:
1)Graphql可以一次性访问多个接口,一般提供给magento2前端使用;
2)RestApi一次只能访问一个接口,一般提供给第三方调用。
具体异同参考:GraphQL vs REST APIs 完整指南-CSDN博客
(1)magento2中要新增Graphql接口需要执行以下几个步骤:
a)首先要在etc/目录下新建一个schema.graphqls文件,在文件中声明新增的是query还是mutation类型。这里以query举例,声明了一个Graphql接口getProduct2VendorInfo,入参为itemId,int类型,返回值为TodoList类型,TodoList定义在下方,Item是ToDoList类型中的嵌套类型,同样在文件中声明。
官方文档:Extend an existing GraphQL schema
type Query {
getProduct2VendorInfo(itemId: Int): TodoList
@resolver(class: "Bcn\\ToDoCrud\\Model\\Resolver\\GetToDoListResolver")
@doc(description: "get todoList item detail.")
}
type TodoList {
items: [Item] @doc(description: "To do list.")
code: String @doc(description: "Response status code.")
}
type Item {
itemId: Int
content: String @doc(description: "Detail of the item.")
}
b) 在Model/下新建目录Resolver,之后在Resolver目录下新建Graphql接口处理类GetToDoListResolver(注:接口处理类一定要实现Magento\Framework\GraphQl\Query\下的ResolverInterface接口),逻辑同RestApi,只不过访问方式不同。
官方文档:GraphQL resolvers
<?php
namespace Bcn\ToDoCrud\Model\Resolver;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Bcn\ToDoCrud\Model\ResourceModel\ToDoList\CollectionFactory;
use phpDocumentor\Reflection\Types\Collection;
class GetToDoListResolver implements ResolverInterface
{
public $collectionFactory;
public function __construct(CollectionFactory $collectionFactory)
{
$this->collectionFactory = $collectionFactory;
}
public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
{
$itemId = $args['itemId'];
// $itemId = 2;
$a = $this->collectionFactory->create();
$a->selectById($itemId);
$a->load();
$items = [];
foreach ($a->getItems() as $item) {
array_push($items,[
'itemId'=>$item->getItemId(),
'content'=>$item->getContent()
]);
}
$todoListData = ["items" => $items, "code"=>"200"];
return $todoListData;
}
}
c)执行命令php bin/magento setup:di:compile,在postman访问
其中参数XDEBUG_SESSION_START=13463为编译模式。