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

Pimple Laravel Package

hyperf/pimple

hyperf/pimple 是基于 pimple/pimple 的轻量级 PSR-11 容器组件,提供简单的 ContainerFactory 创建容器与 Provider 注册机制,帮助在非 Hyperf 框架中低成本接入 Hyperf 组件(如 translation/config),便于集成与复用。

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

  1. Install the Package:
    composer require hyperf/pimple hyperf/translation hyperf/config
    
  2. Create a Pimple Container Instance:
    use Hyperf\Pimple\ContainerFactory;
    
    $pimpleContainer = (new ContainerFactory())();
    
  3. Register Hyperf Services:
    $pimpleContainer->register(new class implements \Hyperf\Pimple\ProviderInterface {
        public function register(\Psr\Container\ContainerInterface $container) {
            $container->set(\Hyperf\Contract\ConfigInterface::class, fn() => new \Hyperf\Config\Config([]));
        }
    });
    
  4. Resolve a Service:
    $config = $pimpleContainer->get(\Hyperf\Contract\ConfigInterface::class);
    

First Use Case: Translation in Laravel

  1. Bind Translation Services:
    $pimpleContainer->register(new \App\Providers\TranslatorProvider());
    
  2. Use in a Laravel Controller:
    use Hyperf\Contract\TranslatorInterface;
    
    public function __construct(private TranslatorInterface $translator) {}
    
    public function index() {
        return $this->translator->trans('message.hello');
    }
    
    Note: Requires Laravel’s DI to resolve Pimple-bound services (see Implementation Patterns).

Implementation Patterns

1. Hybrid Container Workflow (Laravel + Pimple)

Pattern: Use Pimple as a secondary container for Hyperf services while keeping Laravel’s container primary.

// In a Laravel service provider
public function register() {
    $pimple = (new ContainerFactory())->withProviders([
        \App\Providers\HyperfTranslationProvider::class,
    ]);

    // Bind Pimple to Laravel's container
    $this->app->singleton('hyperf.pimple', fn() => $pimple);
    $this->app->bind(\Hyperf\Contract\TranslatorInterface::class, fn($app) =>
        $app['hyperf.pimple']->get(\Hyperf\Contract\TranslatorInterface::class)
    );
}

When to Use:

  • Isolating Hyperf dependencies (e.g., translation, RPC) from core Laravel logic.
  • Avoiding conflicts between Laravel’s and Hyperf’s service bindings.

2. Provider-Based Registration

Pattern: Extend ProviderInterface to register Hyperf services.

// Example: Hyperf Translation Provider for Laravel
class HyperfTranslationProvider implements \Hyperf\Pimple\ProviderInterface {
    public function register(\Psr\Container\ContainerInterface $container) {
        $container->set(\Hyperf\Contract\ConfigInterface::class, fn() =>
            new \Hyperf\Config\Config(config('hyperf'))
        );

        $container->set(\Hyperf\Contract\TranslatorLoaderInterface::class, fn($c) => new \Hyperf\Translation\FileLoader(
            $c->get(\Hyperf\Utils\Filesystem\Filesystem::class),
            storage_path('lang')
        ));

        $container->set(\Hyperf\Contract\TranslatorInterface::class, fn($c) =>
            new \Hyperf\Translation\Translator(
                $c->get(\Hyperf\Contract\TranslatorLoaderInterface::class),
                config('app.locale')
            )
        );
    }
}

Integration Tip:

  • Reuse Laravel’s config() helper to avoid hardcoding paths.
  • Bind Filesystem to Pimple using Laravel’s filesystem:
    $container->set(\Hyperf\Utils\Filesystem\Filesystem::class, fn() =>
        new \Hyperf\Utils\Filesystem\Filesystem(storage_path())
    );
    

3. Service Resolution in Laravel

Pattern: Resolve Pimple-bound services in Laravel controllers/services.

// Option 1: Direct Pimple Resolution (if bound to Laravel's container)
public function __construct(private \Psr\Container\ContainerInterface $pimple) {
    $this->translator = $pimple->get(\Hyperf\Contract\TranslatorInterface::class);
}

// Option 2: Laravel DI (preferred)
public function __construct(private \Hyperf\Contract\TranslatorInterface $translator) {}

Tip:

  • Use constructor injection with Laravel’s DI to maintain consistency.
  • For dynamic resolution, bind Pimple to Laravel’s container as shown in Hybrid Container Workflow.

4. Configuration Management

Pattern: Share Laravel config with Pimple.

$pimpleContainer->set(\Hyperf\Contract\ConfigInterface::class, fn() =>
    new \Hyperf\Config\Config([
        'translation' => [
            'locale' => config('app.locale'),
            'path' => storage_path('lang/hyperf'),
        ],
    ])
);

Tip:

  • Override Hyperf’s default config with Laravel’s config() values.
  • Use config_path('hyperf.php') for Hyperf-specific settings.

5. Testing with Pimple

Pattern: Mock Pimple services in Laravel tests.

public function testTranslation() {
    $pimple = (new ContainerFactory())->withProviders([HyperfTranslationProvider::class]);
    $pimple->set(\Hyperf\Contract\TranslatorInterface::class, $this->createMock(TranslatorInterface::class));

    $this->app->instance('hyperf.pimple', $pimple);

    $this->assertTrue(true); // Test logic using $this->translator
}

Tip:

  • Use Laravel’s app()->instance() to override Pimple bindings in tests.
  • Mock Hyperf interfaces (e.g., TranslatorInterface) to isolate tests.

Gotchas and Tips

Pitfalls

  1. Container Isolation Issues:

    • Problem: Services bound to Pimple may conflict with Laravel’s container if not properly isolated.
    • Fix: Use scoped bindings or namespaced keys (e.g., hyperf.translator).
    • Example:
      $pimple->set('hyperf.translator', $translator); // Avoids collision with Laravel's translator
      
  2. Hyperf-Specific Assumptions:

    • Problem: Hyperf’s make() helper or ApplicationContext won’t work in Laravel.
    • Fix: Replace with Laravel’s app() or manual instantiation:
      // Instead of: make(Translator::class)
      $translator = new \Hyperf\Translation\Translator($loader, $locale);
      
  3. Circular Dependencies:

    • Problem: Pimple may not handle circular dependencies as gracefully as Laravel’s container.
    • Fix: Use lazy loading or interface-based binding:
      $container->set(ServiceInterface::class, fn($c) => new Service($c->get(DependencyInterface::class)));
      
  4. Configuration Overrides:

    • Problem: Hyperf’s config may override Laravel’s settings if not managed carefully.
    • Fix: Merge configs explicitly:
      $hyperfConfig = new \Hyperf\Config\Config([
          'translation' => array_merge(
              config('hyperf.translation', []),
              ['locale' => config('app.locale')]
          ),
      ]);
      
  5. Performance Overhead:

    • Problem: Nested container lookups (Laravel → Pimple) may add latency.
    • Fix: Cache Pimple-bound services in Laravel’s container:
      $this->app->singleton(\Hyperf\Contract\TranslatorInterface::class, fn($app) =>
          $app['hyperf.pimple']->get(\Hyperf\Contract\TranslatorInterface::class)
      );
      

Debugging Tips

  1. Service Not Found:

    • Check: Verify the service is registered in Pimple’s providers.
    • Debug: Dump Pimple’s keys:
      print_r(array_keys($pimple->getKeys()));
      
    • Fix: Ensure the provider’s register() method is called.
  2. Binding Conflicts:

    • Check: Use getKeys() to list all bindings in both containers.
    • Fix: Prefix Pimple bindings (e.g., hyperf.) to avoid collisions.
  3. Hyperf-Specific Errors:

    • Check: Wrap Hyperf code in try-catch to isolate issues:
      try {
          $translator->trans('key');
      } catch (\Exception $e) {
          Log::error('Hyperf translation failed: '.$e->getMessage());
          return 'fallback';
      }
      

Extension Points

  1. Custom Providers:

    • Extend ProviderInterface to add Hyperf services (e.g., caching, RPC):
      class HyperfCacheProvider implements ProviderInterface {
          public function register($container) {
              $container->set(\Hyperf\Contract\CacheInterface::class, fn() =>
                  new \Hyperf\Cache\Driver\RedisDriver(config('cache.redis'))
              );
          }
      }
      
  2. Laravel Service Provider Wrapper:

    • Create a Laravel service provider to manage Pimple
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