Install the Package
composer require d3mo17/colja
Configure the Bundle
Enable the bundle in config/bundles.php:
return [
// ...
DMo\Colja\ColjaBundle::class => ['all' => true],
];
Define a GraphQL Schema
Create a schema file (e.g., config/graphql/schema.graphqls) with basic types and queries:
type Query {
hello: String
}
Configure Schema Path
Update config/packages/d_mo_colja.yaml:
d_mo_colja:
schema_path: '%kernel.project_dir%/config/graphql/schema.graphqls'
resolvers:
Query:
hello: ['App\Resolver\HelloResolver', 'resolveHello']
Create a Resolver
Implement AbstractResolver and define the resolver method:
namespace App\Resolver;
use DMo\Colja\GraphQL\AbstractResolver;
class HelloResolver extends AbstractResolver
{
public function resolveHello($root, $args, $context, $info)
{
return 'Hello, GraphQL!';
}
}
Test the Endpoint
Send a POST request to /graphql with the query:
{
"query": "{ hello }"
}
Modular Schema Files
Extend the base schema with additional files (e.g., mutations.graphqls, types.graphqls) and reference them in d_mo_colja.yaml:
d_mo_colja:
schema_path: '%kernel.project_dir%/config/graphql/schema.graphqls'
schema_extensions:
- '%kernel.project_dir%/config/graphql/types.graphqls'
- '%kernel.project_dir%/config/graphql/mutations.graphqls'
Dynamic Schema Loading Use environment variables or runtime logic to switch schemas (e.g., for staging/production).
Dependency Injection
Access Symfony services (e.g., Doctrine, HTTP client) via $context or the injected ResolverManager:
public function resolveUser($root, $args, $context, $info)
{
$entityManager = $context->get('doctrine')->getManager();
$user = $entityManager->find(User::class, $args['id']);
return $user;
}
Input Validation
Validate $args using Symfony’s Validator:
use Symfony\Component\Validator\Validator\ValidatorInterface;
public function resolveCreateUser($root, $args, $context, $info)
{
$validator = $context->get('validator');
$errors = $validator->validate($args['input']);
if (count($errors) > 0) {
throw new \RuntimeException((string) $errors);
}
// Proceed with creation
}
Batch Loading
Optimize N+1 queries by using DataLoader (integrate via $context):
$dataLoader = $context->get('graphql.data_loader');
$users = $dataLoader->loadMany($args['ids']);
Service Container Access
Laravel’s container can be accessed via $context (Symfony’s container is a facade):
$logger = $context->get('logger');
$logger->info('Resolver executed');
Middleware/Authentication Use Symfony’s security component to protect resolvers:
# config/packages/security.yaml
access_control:
- { path: ^/graphql, roles: ROLE_USER }
Event Dispatching Trigger Laravel events from resolvers:
$eventDispatcher = $context->get('event_dispatcher');
$eventDispatcher->dispatch(new UserCreatedEvent($user));
Schema Caching Colja caches the schema by default. Clear the cache after schema changes:
php bin/console cache:clear
Resolver Naming Conflicts Ensure resolver method names match the schema field names exactly (case-sensitive). Use underscores if needed:
type Query { user_profile: User }
resolvers:
Query:
user_profile: ['App\Resolver\UserResolver', 'resolveUserProfile']
Circular Dependencies
Avoid circular references in resolvers (e.g., A calls B, which calls A). Use @defer or batch loading.
Context Injection
The $context parameter is a Symfony ParameterBag. For Laravel-specific services, bind them to Symfony’s container:
// In a Symfony service config (e.g., `config/services.yaml`)
services:
App\Services\MyService:
tags: ['container.service']
Enable GraphQL Playground
Install graphql-playground for interactive testing:
composer require d3mo17/colja-playground
Configure routes in config/routes.yaml:
graphql_playground:
path: /graphql-playground
methods: GET
Logging Resolver Calls Add logging to resolvers for debugging:
public function resolveSomething($root, $args, $context, $info)
{
$context->get('logger')->debug('Resolver args:', $args);
// ...
}
Validation Errors
GraphQL errors may not surface clearly. Check Symfony’s profiler (/profiler) for validation exceptions.
Custom Directives
Extend GraphQL with custom directives by implementing GraphQL\Language\AST\DirectiveNode handlers.
Middleware Pipeline Add middleware to the GraphQL pipeline (e.g., for logging or auth):
d_mo_colja:
middleware:
- App\GraphQL\Middleware\LoggingMiddleware
Custom Scalar Types
Register custom scalars (e.g., for JSON or UUID) via the siler configuration:
d_mo_colja:
siler:
custom_scalars:
Json: App\GraphQL\Scalar\JsonScalar
How can I help you explore Laravel packages today?