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

Pd Api Laravel Package

appaydin/pd-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

Since this is a Symfony bundle, Laravel integration requires Symfony Bridge (symfony/http-kernel-bundle). Start by:

  1. Install the package (via Composer):

    composer require appaydin/pd-api
    
  2. Bridge Symfony Components (if not already present):

    composer require symfony/http-kernel-bundle symfony/framework-bundle
    
  3. Configure the bundle in config/packages/pd_api.yaml (create if missing):

    pd_api:
        zone: ["^/api"]  # Match Laravel's API routes
        default_accept: json
        default_groups: ['default']
        allow_accept: ['json', 'xml']
    
  4. Register the bundle in config/bundles.php:

    return [
        // ...
        Pd\ApiBundle\PdApiBundle::class => ['all' => true],
    ];
    
  5. First Use Case: Basic API Endpoint Extend AbstractApiController in a Laravel controller:

    use Pd\ApiBundle\Controller\AbstractApiController;
    use Symfony\Component\Routing\Annotation\Route;
    
    class ExampleController extends AbstractApiController
    {
        #[Route('/api/test', name: 'api.test', methods: ['GET'])]
        public function test()
        {
            return ['message' => 'Hello, Laravel-Symfony API!'];
        }
    }
    
    • Note: Use symfony/routing annotations or Laravel’s native routing.

Implementation Patterns

1. Controller Structure

  • Base Controller: Always extend AbstractApiController for built-in features (e.g., response formatting, error handling).

    class UserController extends AbstractApiController
    {
        // ...
    }
    
  • Login Trait: Use LoginTrait for JWT authentication (requires lexik/jwt-authentication-bundle):

    use Pd\ApiBundle\Controller\LoginTrait;
    
    class AuthController extends AbstractApiController
    {
        use LoginTrait;
    
        #[Route('/api/login', name: 'api.login', methods: ['POST'])]
        public function login()
        {
            // Handled by trait
        }
    }
    

2. Response Handling

  • Automatic Formatting: The bundle normalizes responses to JSON or XML based on Accept header.

    return ['data' => $users]; // Auto-converted to JSON/XML
    
  • Error Responses: Errors are standardized under Pd\ApiBundle\Exception\ApiProblem.

    throw new ApiProblem(404, 'User not found');
    

3. Pagination

  • KnpPaginator Support: Normalizers handle pagination responses.
    use Knp\Component\Pager\PaginatorInterface;
    
    #[Route('/api/users', name: 'api.users', methods: ['GET'])]
    public function index(PaginatorInterface $paginator)
    {
        $users = $paginator->paginate(
            $this->userRepository->findAll(),
            $this->request->query->getInt('page', 1),
            10
        );
        return $users; // Auto-normalized
    }
    

4. Request Transformation

  • JSON/XML Body Parsing: The bundle auto-converts request bodies.
    #[Route('/api/users', name: 'api.users', methods: ['POST'])]
    public function store(Request $request)
    {
        $data = $request->getContent(); // Auto-parsed as array
        // ...
    }
    

5. Security Integration

  • JWT Authentication: Configure security.yaml as shown in the README, but adapt for Laravel’s auth:api middleware:
    Route::middleware('auth:api')->group(function () {
        Route::get('/api/protected', [ProtectedController::class, 'index']);
    });
    

Gotchas and Tips

1. Laravel-Symfony Quirks

  • Routing Conflicts: Symfony annotations (@Route) may clash with Laravel’s. Prefer Laravel’s Route::get() or use symfony/routing separately.

    // Laravel-style (recommended)
    Route::get('/api/test', [ExampleController::class, 'test']);
    
    // Symfony-style (may require extra config)
    #[Route('/api/test', name: 'api.test')]
    public function test() { ... }
    
  • Dependency Injection: Use Laravel’s container for services:

    public function __construct(private UserRepository $users)
    {
        // Laravel DI works, but Symfony services may need manual binding.
    }
    

2. Configuration Pitfalls

  • pd_api.zone: Must match Laravel’s API route prefix (e.g., ["^/api"]). Misconfiguration breaks response formatting.
  • default_accept: Set to json for Laravel (XML is niche in PHP ecosystems).
  • Security.yaml: Laravel’s auth:api middleware replaces Symfony’s guard. Ensure JWT routes are excluded from Laravel’s auth middleware.

3. Debugging Tips

  • Response Headers: Check Content-Type headers to verify JSON/XML output.
    curl -H "Accept: application/xml" http://your-api.test/api/test
    
  • Error Messages: Use ApiProblem exceptions for consistent error formats:
    throw new ApiProblem(400, 'Invalid input', ['field' => 'Username is required']);
    
  • Logging: Enable Symfony’s profiler (symfony/web-profiler-bundle) for deep inspection:
    composer require symfony/web-profiler-bundle
    

4. Extension Points

  • Custom Normalizers: Extend Pd\ApiBundle\Normalizer\AbstractNormalizer for new data types.
  • Error Handlers: Override Pd\ApiBundle\Exception\ApiProblemHttpExceptionMapper to customize error responses.
  • Request Transformers: Implement Pd\ApiBundle\Transformer\RequestTransformerInterface for custom body parsing.

5. Performance Notes

  • Caching: Symfony’s serializer is memory-intensive. Cache responses for paginated data:
    $this->cache->set('users_page_1', $users, 300); // 5-minute cache
    
  • Validation: Use Laravel’s built-in validation (e.g., Validator) instead of Symfony’s Validator to avoid duplication.

6. Community Gaps

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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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