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 Service Bundle Laravel Package

ehann/web-service-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Laravel project via Composer:

    composer require ehann/web-service-bundle
    

    Register the service provider in config/app.php under providers:

    Ehann\WebServiceBundle\WebServiceBundle::class,
    
  2. Basic Configuration Publish the default config (if needed) and adjust in config/webservice.php:

    php artisan vendor:publish --provider="Ehann\WebServiceBundle\WebServiceBundle" --tag=config
    
  3. First Use Case: Auto-Deserialization Define a request class (e.g., CreateUserRequest) extending Ehann\WebServiceBundle\Request\Request:

    namespace App\Http\Requests;
    
    use Ehann\WebServiceBundle\Request\Request;
    
    class CreateUserRequest extends Request
    {
        public $name;
        public $email;
    }
    

    Use it in a controller:

    use App\Http\Requests\CreateUserRequest;
    
    public function store(CreateUserRequest $request)
    {
        $user = new User();
        $user->name = $request->name; // Auto-deserialized
        $user->email = $request->email;
        $user->save();
    }
    

Implementation Patterns

1. Request/Response Serialization

  • Incoming Requests: Automatically map JSON/XML form data to public properties in your request class.
    // Automatically binds to $request->age
    public $age;
    
  • Outgoing Responses: Serialize model/collection responses to JSON/XML:
    use Ehann\WebServiceBundle\Response\Response;
    
    return Response::json($user, 201); // Auto-serializes user data
    

2. Validation Integration

Combine with Laravel’s validation by overriding rules():

public function rules()
{
    return [
        'email' => 'required|email',
        'age'   => 'integer|min:18',
    ];
}

The bundle handles validation errors in a standardized format.

3. Custom Serializers

Extend default behavior by implementing Ehann\WebServiceBundle\Serializer\SerializerInterface:

namespace App\Services;

use Ehann\WebServiceBundle\Serializer\SerializerInterface;

class CustomSerializer implements SerializerInterface
{
    public function serialize($data) { /* ... */ }
    public function deserialize($data, $class) { /* ... */ }
}

Register it in config/webservice.php:

'serializers' => [
    'json' => App\Services\CustomSerializer::class,
],

4. Middleware for API Guarding

Use the bundle’s middleware to enforce JSON/XML content types:

// In App\Http\Kernel.php
protected $middlewareGroups = [
    'web' => [
        // ...
        \Ehann\WebServiceBundle\Http\Middleware\EnsureWebServiceRequest::class,
    ],
];

5. API Resource Transformation

Transform Eloquent models to API responses without bloated controllers:

use Ehann\WebServiceBundle\Response\ResourceResponse;

return ResourceResponse::collection(User::all(), UserResource::class);

Define UserResource to control output fields:

namespace App\Http\Resources;

use Ehann\WebServiceBundle\Response\Resource;

class UserResource extends Resource
{
    public $id;
    public $name;
    public $email;

    public function toArray($request)
    {
        return [
            'id'   => $this->id,
            'name' => $this->name,
        ];
    }
}

Gotchas and Tips

Pitfalls

  1. Property Visibility

    • Only public properties are auto-bound. Private/protected properties require manual handling or custom deserialization.
    • Fix: Use protected $fillable = ['email', 'name']; and implement deserialize() in your request class.
  2. Circular References

    • Serializing nested objects (e.g., User->posts) may cause infinite loops.
    • Fix: Use ignoredAttributes in config/webservice.php or override serialize() to handle cycles.
  3. Overriding Default Serializers

    • If you replace the default serializer, ensure it supports all expected formats (JSON/XML).
    • Tip: Extend the base serializer instead of rewriting from scratch.
  4. Validation Timing

    • Validation runs after deserialization. If your request class has logic in the constructor, it may interfere with validation.
    • Tip: Move logic to with() or handle() methods.
  5. Middleware Order

    • Place EnsureWebServiceRequest before your API routes to avoid bypassing serialization.
    • Example:
      Route::middleware(['api', 'ensure.webservice'])->group(function () { ... });
      

Debugging Tips

  • Enable Debug Mode Set 'debug' => true in config/webservice.php to log deserialization/serialization steps.

  • Inspect Raw Data Access raw input via $request->getContent() or $request->getData() to debug binding issues.

  • Custom Error Handling Override handle() in your request class to catch deserialization errors:

    public function handle()
    {
        try {
            parent::handle();
        } catch (\Exception $e) {
            return response()->json(['error' => 'Deserialization failed'], 400);
        }
    }
    

Extension Points

  1. Custom Request Classes Extend Ehann\WebServiceBundle\Request\Request to add pre-processing:

    public function prepareForDeserialization()
    {
        $this->data['email'] = strtolower($this->data['email']);
    }
    
  2. Dynamic Property Binding Use deserialize() to handle dynamic or nested data:

    public function deserialize(array $data)
    {
        $this->name = $data['user']['name'];
    }
    
  3. Event Listeners Listen to webservice.deserialized or webservice.serialized events for post-processing:

    // In EventServiceProvider
    protected $listen = [
        'webservice.deserialized' => [
            \App\Listeners\LogRequestData::class,
        ],
    ];
    
  4. Testing Mock the bundle’s serializer in tests:

    $this->app->instance(
        \Ehann\WebServiceBundle\Serializer\SerializerInterface::class,
        MockSerializer::class
    );
    

Performance Considerations

  • Caching Serializers: If using custom serializers, cache compiled classes for repeated requests.
  • Batch Processing: For bulk operations, deserialize once and reuse the data object:
    $requests = CreateUserRequest::deserializeMany($rawData);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui