I made a graphql controller that resolves information about category’s from doctrine-orm. The problem starts when I input following command to my terminal:
curl -X POST http://localhost:8000/graphql -H "Content-Type: application/json" -d '{"query": "{ category(id: 1) { category_id category_name } }"}'
Category class
<?php
namespace AppModels;
use AppEntityTechCategory;
use AppEntityClothCategory;
use DoctrineORMMapping as ORM;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
#[ORMEntity]
#[ORMTable(name: 'category')]
#[ORMInheritanceType("SINGLE_TABLE")]
#[ORMDiscriminatorColumn(name: 'discr', type: 'string')]
#[ORMDiscriminatorMap(['tech' => TechCategory::class, 'cloth' => ClothCategory::class])]
class Category
{
#[ORMId]
#[ORMColumn(type: 'integer')]
#[ORMGeneratedValue]
protected $category_id;
#[ORMColumn(type: 'string')]
protected $category_name;
//There can be many products to a single category
#[ORMOneToMany(targetEntity: "Product", mappedBy: "category")]
protected Collection $products;
public function __construct()
{
$this->products = new ArrayCollection();
}
// Getters and setters...
public function getCategoryId(): int
{
return $this->category_id;
}
public function getCategory(): string
{
return $this->category_name;
}
public function setCategory(string $category_name): void
{
$this->category_name = $category_name;
}
public function getProducts(): Collection
{
return $this->products;
}
public function addProduct(Product $product): void
{
if (!$this->products->contains($product)) {
$this->products[] = $product;
$product->setCategory($this);
}
}
public function removeProduct(Product $product): void
{
if ($this->products->contains($product)) {
$this->products->removeElement($product);
if ($product->getCategory() === $this) {
$product->getCategory(null);
}
}
}
}
Graphql Controller
<?php
namespace AppController;
use AppModelsCategory;
use GraphQLGraphQL as GraphQLBase;
use GraphQLTypeDefinitionObjectType;
use GraphQLTypeDefinitionType;
use GraphQLTypeSchema;
use GraphQLTypeSchemaConfig;
use RuntimeException;
use Throwable;
use DoctrineORMEntityManagerInterface;
class GraphQL {
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function handle() {
try {
//Category: category_id, category_name, products
$categoryType = new ObjectType([
'name' => 'Category',
'fields' => [
'category_id' => Type::int(),
'category_name' => Type::string(),
]
]);
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'category' => [
'type' => $categoryType,
'args' => [
'id' => ['type' => Type::int()],
],
'resolve' => function ($rootValue, array $args) {
$categoryId = $args['id'];
return $this->entityManager->getRepository(Category::class)->find($categoryId);
},
],
],
]);
$schema = new Schema(
(new SchemaConfig())
->setQuery($queryType)
// ->setMutation($mutationType)
);
$rawInput = file_get_contents('php://input');
if ($rawInput === false) {
throw new RuntimeException('Failed to get php://input');
}
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = $input['variables'] ?? null;
// $rootValue = ['prefix' => 'You said: '];
$result = GraphQLBase::executeQuery($schema, $query, null, null, $variableValues);
$output = $result->toArray();
} catch (Throwable $e) {
$output = [
'error' => [
'message' => $e->getMessage(),
],
];
}
header('Content-Type: application/json; charset=UTF-8');
return json_encode($output);
}
}
Index.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../app/Config/bootstrap.php';
use FastRouteRouteCollector;
use FastRouteDispatcher;
use AppControllerGraphQL;
use DoctrineORMEntityManagerInterface;
$graphQLController = new GraphQL($entityManager);
$dispatcher = FastRoutesimpleDispatcher(function(FastRouteRouteCollector $r) use ($graphQLController) {
$r->post('/graphql', [$graphQLController, 'handle']);
});
$routeInfo = $dispatcher->dispatch(
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI']
);
switch ($routeInfo[0]) {
case FastRouteDispatcher::NOT_FOUND:
// ... 404 Not Found
http_response_code(404);
echo '404 Not Found';
break;
case FastRouteDispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $routeInfo[1];
// ... 405 Method Not Allowed
http_response_code(405);
echo '405 Method Not Allowed';
break;
case FastRouteDispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
echo call_user_func($handler, $vars);
break;
}
Output that I get when I run the curl command is
{"data":{"category":{"category_id":null,"category_name":null}}}
Thoughts
Doctrine is setup correctly I can list rows from mysql database trough entity manager however problems start when I try to query them out. I don’t know if it’s because there is products array in my category class or because there are sub classes to my category class.
Any help would be greatly appreciated!