Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Graphql Mapper Bundle Laravel Package

arthem/graphql-mapper-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require arthem/graphql-mapper-bundle
    
  2. Enable the Bundle Add to app/AppKernel.php:

    new Arthem\Bundle\GraphQLBundle\ArthemGraphQLBundle(),
    
  3. Define Your Schema Create app/config/graphql_schema.yml with a basic schema:

    types:
        Query:
            fields:
                hello:
                    type: String
                    resolve: "function() { return 'World'; }"
    
  4. Configure the Bundle In app/config/config.yml:

    arthem_graphql:
        mapping:
            files:
                - %kernel.root_dir%/config/graphql_schema.yml
    
  5. Set Up Routing Add to app/config/routing.yml:

    arthem_graphql:
        resource: "@ArthemGraphQLBundle/Resources/config/routing.yml"
        prefix: /graphql
    
  6. Test the Endpoint Send a POST request to /graphql with:

    {
        "query": "{ hello }"
    }
    

First Use Case

Map a Doctrine entity to a GraphQL type:

# app/config/graphql_schema.yml
types:
    User:
        fields:
            id:
                type: Int
                resolve: "function($obj) { return $obj->getId(); }"
            name:
                type: String
                resolve: "function($obj) { return $obj->getName(); }"

Implementation Patterns

Mapping Doctrine Entities

  1. Define Types Use YAML to map entities to GraphQL types:

    types:
        Product:
            fields:
                id: { type: Int, resolve: "function($obj) { return $obj->getId(); }" }
                name: { type: String, resolve: "function($obj) { return $obj->getName(); }" }
                price: { type: Float, resolve: "function($obj) { return $obj->getPrice(); }" }
    
  2. Resolve with Services Inject services into resolvers:

    types:
        Order:
            fields:
                total:
                    type: Float
                    resolve: "@app.service.order_calculator.calculate"
    
  3. Query and Mutations Define root-level operations:

    types:
        Query:
            fields:
                products:
                    type: "[Product]"
                    args:
                        limit: { type: Int }
                    resolve: "@app.repository.product.findAll"
        Mutation:
            fields:
                createProduct:
                    type: Product
                    args:
                        name: { type: String }
                        price: { type: Float }
                    resolve: "@app.service.product.create"
    

Integration with Symfony

  1. Dependency Injection Use Symfony’s DI to pass services to resolvers:

    types:
        User:
            fields:
                posts:
                    type: "[Post]"
                    resolve: "@app.service.user.getPosts"
    
  2. Authentication Secure endpoints via Symfony’s security system:

    # app/config/security.yml
    access_control:
        - { path: ^/graphql, roles: ROLE_USER }
    
  3. Validation Validate input args using Symfony’s Validator:

    types:
        Mutation:
            fields:
                updateUser:
                    type: User
                    args:
                        id: { type: Int }
                        name: { type: String, validate: "NotBlank" }
                    resolve: "@app.service.user.update"
    

Workflows

  1. Schema-First Development

    • Define schema in YAML first.
    • Generate API clients (e.g., GraphQL Code Generator) from the schema.
  2. Incremental Adoption

    • Start with read-only queries.
    • Gradually add mutations as needed.
  3. Testing

    • Use PHPUnit to test resolvers:
      public function testHelloResolver()
      {
          $this->client->request('POST', '/graphql', [
              'json' => ['query' => '{ hello }']
          ]);
          $this->assertEquals('World', $this->client->getResponse()->getContent());
      }
      

Gotchas and Tips

Pitfalls

  1. Outdated Dependencies

    • The package relies on arthem/graphql-mapper (last updated in 2016). Ensure compatibility with your PHP/Doctrine versions.
    • Workaround: Fork and update dependencies if needed.
  2. YAML Schema Limitations

    • Complex logic in resolvers may require PHP callbacks, which can clutter YAML.
    • Tip: Use Symfony services for complex logic.
  3. No Built-in Playground

    • Unlike modern tools (e.g., graphql-php/graphql-server), this bundle lacks a GUI playground.
    • Tip: Use tools like GraphiQL or Altair with a proxy.
  4. Caching Schema

    • Schema changes require a cache clear (php bin/console cache:clear).
    • Tip: Use environment variables to toggle schema caching in development.
  5. Error Handling

    • Errors in resolvers may not be user-friendly.
    • Tip: Wrap resolvers in try-catch blocks and return structured errors:
      types:
          Query:
              fields:
                  riskyOperation:
                      type: String
                      resolve: |
                          try {
                              return $this->doRiskyStuff();
                          } catch (\Exception $e) {
                              return "Error: " . $e->getMessage();
                          }
      

Debugging

  1. Enable Debug Mode Set app.debug: true in config.yml to see detailed errors.

  2. Log Resolver Calls Add logging to resolvers:

    types:
        Query:
            fields:
                debug:
                    type: String
                    resolve: |
                        \Symfony\Component\Debug\Debug::dump($obj);
                        return "Logged!";
    
  3. Validate Schema Use the graphql-mapper CLI tool to validate your YAML schema:

    vendor/bin/graphql-mapper validate app/config/graphql_schema.yml
    

Extension Points

  1. Custom Directives Extend the schema with custom directives (if supported by the underlying mapper):

    directives:
        auth:
            locations: [QUERY, MUTATION]
            args:
                role: { type: String }
    
  2. Middleware Add middleware to the GraphQL pipeline (if the mapper supports it):

    arthem_graphql:
        middleware:
            - "@app.middleware.graphql_logger"
    
  3. Subscriptions The bundle may not support subscriptions out of the box. For real-time features:

    • Tip: Use a separate WebSocket layer (e.g., Ratchet) and integrate with this bundle’s queries.

Performance Tips

  1. Batch Loading Use Doctrine’s Hydrator or ResultCache to optimize resolver performance:

    types:
        User:
            fields:
                posts:
                    type: "[Post]"
                    resolve: "@app.service.user.getPostsWithBatchLoading"
    
  2. Lazy Loading Avoid N+1 queries by eager-loading associations in resolvers:

    types:
        User:
            fields:
                orders:
                    type: "[Order]"
                    resolve: "@app.service.user.getOrdersWithEagerLoading"
    
  3. Caching Resolvers Cache resolver results for static data:

    types:
        Query:
            fields:
                config:
                    type: String
                    resolve: "@app.cache.graphql_config"
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope