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

Web Services Bundle Laravel Package

ac/web-services-bundle

Symfony bundle providing generic REST API workflow tools: request lifecycle events, JMS-based deserialization into existing objects, validation error handling, configurable response formats (JSON/XML/JSONP/YML), and per-path settings for exceptions, response data, JSONP, and headers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ac/web-services-bundle:~0.2.0
    

    Enable the bundle in AppKernel.php:

    new AC\WebServicesBundle\ACWebServicesBundle(),
    
  2. Basic Configuration (app/config/config.yml):

    ac_web_services:
        default_format: json  # or xml, jsonp, yml
        include_response_data: true
    
  3. First Use Case: Create a controller to handle a simple API endpoint:

    use AC\WebServicesBundle\Event\ApiEvent;
    use Symfony\Component\HttpFoundation\Request;
    
    class ApiController extends Controller
    {
        public function indexAction(Request $request)
        {
            $event = new ApiEvent($request, $this->get('request_stack'));
            $this->get('event_dispatcher')->dispatch('api.request', $event);
    
            // Your logic here
            return $this->get('ac_web_services.response_factory')->createResponse(
                ['data' => 'Hello, API!'],
                200
            );
        }
    }
    

Implementation Patterns

Event-Driven Workflow

Leverage the request lifecycle events to centralize API logic:

// In a service or controller
$event = new ApiEvent($request, $this->get('request_stack'));
$this->get('event_dispatcher')->dispatch('api.request', $event);

// Listen to events in a service
public function onApiRequest(ApiEvent $event)
{
    $event->setData(['preprocessed' => true]);
}

Register listeners in services.yml:

services:
    app.api_listener:
        class: AppBundle\EventListener\ApiListener
        tags:
            - { name: kernel.event_listener, event: api.request, method: onApiRequest }

Deserialization with JMS Serializer

Use the object deserializer to map incoming JSON/XML to entities:

use AC\WebServicesBundle\Serializer\ObjectDeserializer;

// In a controller or service
$deserializer = $this->get('ac_web_services.object_deserializer');
$entity = $deserializer->deserialize($request->getContent(), 'AppBundle\Entity\User', 'json');

Configure JMS Serializer (config.yml):

jms_serializer:
    metadata:
        directories:
            AppBundle: %kernel.root_dir%/Resources/config/serializer

Validation Error Handling

Convert Symfony validator errors into API-friendly responses:

use AC\WebServicesBundle\Validator\ErrorMapper;

$validator = $this->get('validator');
$errors = $validator->validate($entity);

$errorMapper = $this->get('ac_web_services.error_mapper');
$response = $errorMapper->mapErrors($errors);

Response Customization

Extend the response factory for consistent API responses:

// Override the default response factory (e.g., in a compiler pass)
public function createResponse($data, $status = 200, array $headers = [])
{
    $response = parent::createResponse($data, $status, $headers);
    $response->headers->set('X-API-Version', '1.0');
    return $response;
}

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • The last release is from 2014. Avoid for production; prefer FOSRestBundle or modern alternatives like API Platform.
    • Mitigation: Use this only for legacy projects or as a learning tool.
  2. JMS Serializer Dependency:

    • Requires jms/serializer-bundle (not included by default). Add it manually:
      composer require jms/serializer-bundle
      
  3. Event Dispatching:

    • Events like api.request are not standard Symfony events. Document them in your codebase to avoid confusion.
  4. Response Formats:

    • The default_format config is case-sensitive (json, not JSON).

Debugging Tips

  1. Event Debugging:

    • Dump dispatched events in a listener:
      public function onApiRequest(ApiEvent $event)
      {
          var_dump($event->getData());
      }
      
  2. Deserialization Issues:

    • Validate JMS metadata files (.yml/.xml) for typos or missing properties.
    • Enable JMS debug mode:
      jms_serializer:
          debug: %kernel.debug%
      
  3. Response Headers:

    • Override headers in the response factory if the bundle doesn’t respect your Accept header:
      $response->setPublic();
      $response->setMaxAge(3600);
      

Extension Points

  1. Custom Response Formats:

    • Extend the AC\WebServicesBundle\Response\ResponseFactory class to add support for new formats (e.g., GraphQL).
  2. Event Subscribers:

    • Create a subscriber to modify request/response globally:
      class GlobalApiSubscriber implements EventSubscriberInterface
      {
          public static function getSubscribedEvents()
          {
              return ['api.request' => 'onRequest'];
          }
      
          public function onRequest(ApiEvent $event)
          {
              $event->addData(['timestamp' => time()]);
          }
      }
      
  3. Validation Groups:

    • Use JMS Serializer’s @Groups to control deserialization:
      # config/serializer/User.yml
      AppBundle\Entity\User:
          properties:
              email:
                  groups: [registration]
      
    • Pass the group to the deserializer:
      $entity = $deserializer->deserialize($data, 'AppBundle\Entity\User', 'json', ['groups' => ['registration']]);
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware