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

Api2Symfony Laravel Package

creads/api2symfony

Converts API Platform endpoints into Symfony-friendly client code from your OpenAPI/Swagger spec. Generates models and request classes to speed up integration with API Platform services and keep your Symfony app’s API clients consistent and maintainable.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require creads/api2symfony
    

    (Note: Due to archival, verify compatibility with your Symfony version.)

  2. Prepare OpenAPI/Swagger Spec Ensure your api_spec.yaml or api_spec.json is valid and follows OpenAPI 2.0/3.x standards.

  3. Generate Initial Code

    vendor/bin/api2symfony generate --spec=path/to/api_spec.yaml --output=src/
    

    (Default output: src/Controller/, src/Client/, src/DTO/)

  4. First Use Case: API Server Stub

    • Navigate to generated src/Controller/ to find auto-created controllers (e.g., UserController).
    • Test endpoints (e.g., GET /users/{id}) with Symfony’s built-in server:
      php bin/console server:run
      

Where to Look First

  • Generated Files:
    • src/Controller/ → Symfony controllers with route annotations.
    • src/Client/ → Typed API clients (e.g., UserApiClient).
    • src/DTO/ → Data Transfer Objects (DTOs) with validation rules.
  • Configuration: Check config/packages/api2symfony.yaml (if auto-generated) for custom templates or overrides.
  • Documentation: (Limited due to archival; refer to Symfony’s OpenAPI tools for parallels.)

Implementation Patterns

Workflow: API-Driven Development

  1. Spec-First Development

    • Update api_spec.yaml → Regenerate code:
      vendor/bin/api2symfony regenerate --spec=updated_spec.yaml
      
    • Override generated files in src/ (avoid merging conflicts by using --force sparingly).
  2. Controller Integration

    • Extend generated controllers to add business logic:
      // src/Controller/UserController.php (generated)
      namespace App\Controller;
      use App\DTO\UserDTO;
      
      class UserController extends AbstractController {
          public function getUser(UserDTO $user): UserDTO {
              // Add custom logic here
              return $user; // Auto-serialized to JSON
          }
      }
      
  3. Client Usage

    • Inject the auto-generated client into services:
      use App\Client\UserApiClient;
      
      class UserService {
          public function __construct(private UserApiClient $client) {}
      
          public function fetchUser(int $id): array {
              return $this->client->getUser($id)->toArray();
          }
      }
      
  4. Validation & Serialization

    • Leverage DTOs for automatic validation:
      # api_spec.yaml
      definitions:
        User:
          properties:
            email:
              type: string
              format: email
      
      (Generates UserDTO with Symfony Validator constraints.)

Integration Tips

  • Symfony Flex Compatibility: Ensure composer.json includes:
    "require": {
        "symfony/framework-bundle": "^5.0|^6.0",
        "symfony/validator": "^5.0|^6.0"
    }
    
  • Custom Templates: Override templates in config/api2symfony/templates/ to modify generated code (e.g., add traits).
  • API Platform Synergy: Combine with API Platform for hydrators/serializers if needed.
  • Testing: Use generated clients in PHPUnit:
    $client = new UserApiClient('http://api.test');
    $response = $client->getUser(1);
    $this->assertEquals('john@example.com', $response->email);
    

Gotchas and Tips

Pitfalls

  1. Archived Package Risks

    • No Active Maintenance: Last release in 2016 may lack Symfony 6.x/7.x support. Workaround: Fork the repo and update dependencies (e.g., symfony/yaml, symfony/validator).
    • Deprecated Features: OpenAPI 3.x may not be fully supported. Workaround: Use OpenAPI 2.0 or patch the generator.
  2. Regeneration Overwrites

    • Running regenerate without --force fails if files were manually modified. Tip: Use git diff to track changes or stash modifications before regenerating.
  3. Circular Dependencies

    • Complex specs with circular references (e.g., User references Order, which references User) may break generation. Fix: Simplify the spec or post-process generated DTOs.
  4. Validation Gaps

    • Custom validation rules in the spec (e.g., @assert) may not generate correctly. Tip: Manually add constraints to DTOs after generation.

Debugging

  • Generator Errors: Check logs in var/log/dev.log or run with --verbose:
    vendor/bin/api2symfony generate --verbose
    
  • Broken Controllers: Ensure routes are loaded in config/routes.yaml:
    controllers:
        resource: ../src/Controller/
        type: annotation
    
  • DTO Issues: Validate with Symfony’s validator:
    $validator = $this->container->get('validator');
    $errors = $validator->validate($dto);
    

Extension Points

  1. Custom DTO Mappers Override src/DTO/AbstractDTO.php to add global methods (e.g., toArray()):

    abstract class AbstractDTO {
        public function toArray(): array {
            return (new ArrayTransformer())->transform($this);
        }
    }
    
  2. Event Listeners Attach listeners to generated controllers for pre/post-processing:

    # config/services.yaml
    services:
        App\EventListener\ApiEventListener:
            tags:
                - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
    
  3. Template Overrides Copy vendor/creads/api2symfony/templates/ to config/api2symfony/templates/ and modify:

    • Controller.twig → Add middleware or annotations.
    • DTO.twig → Extend validation or add methods.
  4. API Client Extensions Extend generated clients to add retry logic or logging:

    class CustomUserApiClient extends UserApiClient {
        public function getUser(int $id): UserDTO {
            $response = parent::getUser($id);
            $this->logRequest($response);
            return $response;
        }
    }
    

Pro Tips

  • Partial Regeneration: Use --only=controllers or --only=clients to regenerate specific parts.
  • Spec Validation: Validate specs before generation with Swagger Editor.
  • CI/CD Integration: Add regeneration to your pipeline to enforce spec compliance:
    # .github/workflows/regenerate.yml
    jobs:
      regenerate:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - run: composer install
          - run: vendor/bin/api2symfony regenerate --spec=api_spec.yaml
          - run: git diff --exit-code
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky