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

Common Bundle Laravel Package

elasticms/common-bundle

Shared library bundle for elasticMS, used by the Core and Client Helper bundles. Provides common code, utilities, and services to keep the platform consistent. Documentation available on the EMS project site; issues and PRs via the elasticMS monorepo.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle:

    composer require elasticms/common-bundle
    

    Ensure your composer.json includes Laravel’s Symfony bridge:

    "require": {
        "illuminate/support": "^9.0"
    }
    
  2. Register the Bundle: In config/app.php, add the bundle to the extra.bundles array (if using Symfony’s bridge) or create a custom service provider:

    // app/Providers/EMSCommonServiceProvider.php
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    use EMS\CommonBundle\EMSCommonBundle;
    
    class EMSCommonServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->registerBundle(new EMSCommonBundle());
        }
    }
    

    Then register it in config/app.php:

    'providers' => [
        // ...
        App\Providers\EMSCommonServiceProvider::class,
    ],
    
  3. First Use Case: Shared Validation Use the bundle’s validator traits in your Laravel controllers:

    use EMS\CommonBundle\Validator\TenantAwareValidator;
    
    class ContentController extends Controller
    {
        protected $validator;
    
        public function __construct(TenantAwareValidator $validator)
        {
            $this->validator = $validator;
        }
    
        public function store(Request $request)
        {
            if (!$this->validator->validate($request->all())) {
                return response()->json(['errors' => $this->validator->getErrors()], 422);
            }
            // Proceed with logic
        }
    }
    
  4. Verify Configuration: Check config/packages/ems_common.yaml (if auto-generated) or create a Laravel-compatible config file:

    // config/ems_common.php
    return [
        'tenant_aware' => true,
        'default_locale' => 'en_US',
    ];
    

Implementation Patterns

Core Workflows

1. Dependency Injection & Service Binding

Leverage Laravel’s service container to bind bundle services:

// In a service provider
$this->app->bind(
    \EMS\CommonBundle\Service\ApiClient::class,
    function ($app) {
        return new \EMS\CommonBundle\Service\ApiClient(
            $app['config']['ems_common.api_endpoint']
        );
    }
);

2. Event-Driven Architecture

Adapt Symfony events to Laravel’s event system:

// Listen to EMS events in Laravel
event(new \EMS\CommonBundle\Event\ContentPublishedEvent($content));

Register listeners in EventServiceProvider:

protected $listen = [
    \EMS\CommonBundle\Event\ContentPublishedEvent::class => [
        \App\Listeners\LogContentPublished::class,
    ],
];

3. Shared DTOs (Data Transfer Objects)

Use bundle DTOs for API requests/responses:

use EMS\CommonBundle\DTO\ContentDTO;

$dto = new ContentDTO();
$dto->setTitle($request->input('title'))
    ->setSlug($request->input('slug'));
$serialized = $dto->toArray();

4. Middleware Integration

Extend bundle middleware for Laravel:

// app/Http/Middleware/HandleEMSRequest.php
namespace App\Http\Middleware;

use Closure;
use EMS\CommonBundle\Middleware\TenantMiddleware;

class HandleEMSRequest
{
    public function __construct(private TenantMiddleware $tenantMiddleware)
    {}

    public function handle($request, Closure $next)
    {
        $this->tenantMiddleware->handle($request);
        return $next($request);
    }
}

5. Configuration Management

Merge Symfony-style config with Laravel:

// In a service provider
$this->mergeConfigFrom(
    __DIR__.'/../../config/ems_common.php',
    'ems_common'
);

Integration Tips

For Laravel Eloquent Models

Extend bundle entities with Laravel models:

namespace App\Models;

use EMS\CommonBundle\Entity\BaseContent;
use Illuminate\Database\Eloquent\Model;

class Content extends Model
{
    use BaseContent; // If the bundle provides traits
}

For API Responses

Standardize responses using bundle helpers:

use EMS\CommonBundle\Response\ApiResponse;

return new ApiResponse(
    $data,
    $statusCode,
    $headers
);

For Logging

Use bundle loggers with Laravel’s logging:

use EMS\CommonBundle\Logger\EMSLogger;

EMSLogger::info('Content updated', ['content_id' => $content->id]);

For Tenant-Aware Logic

Integrate tenant resolution:

use EMS\CommonBundle\Tenant\TenantResolver;

$tenantId = app(TenantResolver::class)->resolve($request);

Gotchas and Tips

Pitfalls

1. Symfony vs. Laravel API Mismatches

  • Issue: Symfony’s HttpFoundation\Request differs from Laravel’s Illuminate\Http\Request. Fix: Use a wrapper or adapter:
    $symfonyRequest = new \Symfony\Component\HttpFoundation\Request(
        $laravelRequest->query->all(),
        $laravelRequest->request->all(),
        []
    );
    

2. Event Dispatcher Conflicts

  • Issue: Symfony’s EventDispatcher may conflict with Laravel’s Events. Fix: Create a facade or service to bridge them:
    // app/Providers/AppServiceProvider.php
    $this->app->singleton(\Symfony\Component\EventDispatcher\EventDispatcherInterface::class, function ($app) {
        return new \Symfony\Component\EventDispatcher\EventDispatcher();
    });
    

3. Configuration Overrides

  • Issue: Bundle expects config/packages/ems_common.yaml. Fix: Manually merge configs in a service provider:
    $this->mergeConfigFrom(__DIR__.'/../../config/ems_common.php', 'ems_common');
    

4. Service Container Binding Conflicts

  • Issue: Duplicate service bindings (e.g., ApiClient). Fix: Unbind the original service first:
    $this->app->rebinding(\EMS\CommonBundle\Service\ApiClient::class, function ($app, $original) {
        return new \App\Services\CustomApiClient($original);
    });
    

5. Undocumented Dependencies

  • Issue: Bundle may require PHP extensions (e.g., intl, gd) or specific Symfony versions. Fix: Check composer.json and test locally:
    composer validate
    composer show elasticms/common-bundle --tree
    

Debugging Tips

Enable Debug Logging

Add to config/logging.php:

'channels' => [
    'ems' => [
        'driver' => 'single',
        'path' => storage_path('logs/ems.log'),
        'level' => 'debug',
    ],
],

Then log bundle interactions:

EMS\CommonBundle\Logger\EMSLogger::debug('Debug message', ['context' => 'key']);

Use Dumpers for Complex Objects

For debugging bundle DTOs or entities:

use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;

$dumper = new HtmlDumper();
$dumper->dump(new VarCloner(), $yourBundleObject);

Check for Deprecated Methods

Use phpstan or psalm to detect deprecated bundle methods:

composer require --dev phpstan/phpstan
vendor/bin/phpstan analyse --level 7

Extension Points

1. Override Bundle Services

Extend or replace bundle services in a service provider:

$this->app->extend(\EMS\CommonBundle\Service\ApiClient::class, function ($app, $original) {
    return new \App\Services\CustomApiClient($original);
});

2. Add Custom Validators

Extend bundle validators:

use EMS\CommonBundle\Validator\AbstractValidator;

class CustomValidator extends AbstractValidator
{
    protected function getRules()
    {
        return [
            'custom_field' => 'required|string|max:255',
        ];
    }
}

3. Create Custom Events

Dispatch custom events alongside bundle events:

event(new \App\Events\ContentUpdatedEvent($content));

4. Extend Bundle Entities

Add methods to bundle entities:

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.
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views