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

Contract Laravel Package

hyperf/contract

Core contracts for Hyperf: a set of lightweight PHP interfaces that define common behaviors across the framework (DI, events, middleware, serialization, etc.). Helps decouple components, improve testability, and keep implementations swappable.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Require the package via Composer:

    composer require hyperf/contract
    

    No additional configuration is needed—it provides only interfaces.

  2. First Use Case Define a service class implementing a Hyperf contract, such as CacheInterface:

    use Hyperf\Contract\CacheInterface;
    
    class RedisCache implements CacheInterface
    {
        public function get($key, $default = null)
        {
            // Redis logic
        }
    
        public function set($key, $value, $ttl = null)
        {
            // Redis logic
        }
    }
    
  3. Where to Look First

    • Explore the src/Contract directory for available interfaces.
    • Refer to the Hyperf documentation for integration examples.
    • Use IDE autocompletion (Hyperf\Contract\) to discover relevant contracts.

Implementation Patterns

Dependency Injection (DI)

Leverage Hyperf’s DI container to bind contracts to implementations:

// In a service provider or configuration file
$container->bind(
    Hyperf\Contract\CacheInterface::class,
    RedisCache::class
);
  • Annotations: Use @Inject to auto-wire dependencies:
    use Hyperf\Di\Annotation\Inject;
    
    class OrderService
    {
        #[Inject]
        public CacheInterface $cache;
    }
    

Middleware & Filters

Implement lifecycle hooks like OnRequest for HTTP processing:

use Hyperf\Contract\OnRequest;

class AuthMiddleware implements OnRequest
{
    public function process($request, Closure $next)
    {
        if (!$request->hasHeader('Authorization')) {
            return new Response(401);
        }
        return $next($request);
    }
}

Register middleware in config/autoload/middlewares.php:

return [
    'http' => [
        AuthMiddleware::class,
    ],
];

Service Abstraction

Define modular boundaries using contracts (e.g., QueueWorkerInterface):

use Hyperf\Contract\QueueWorkerInterface;

class PaymentProcessor implements QueueWorkerInterface
{
    public function handle($job)
    {
        // Process payment
    }
}

Register workers in config/autoload/queues.php:

return [
    'default' => [
        'connection' => 'default',
        'queue' => 'payment',
        'worker' => PaymentProcessor::class,
    ],
];

Event Handling

Use Hyperf\Contract\EventDispatcherInterface for event-driven workflows:

use Hyperf\Contract\EventDispatcherInterface;

class OrderEventDispatcher
{
    public function __construct(
        private EventDispatcherInterface $dispatcher
    ) {}

    public function dispatchOrderCreated($order)
    {
        $this->dispatcher->dispatch(new OrderCreated($order));
    }
}

Configuration Management

Access configurations via Hyperf\Contract\ConfigInterface:

use Hyperf\Contract\ConfigInterface;

class AppConfig
{
    public function __construct(private ConfigInterface $config) {}

    public function getAppName()
    {
        return $this->config->get('app.name');
    }
}

Database Abstraction

Use Hyperf\Contract\DatabaseInterface for database operations:

use Hyperf\Contract\DatabaseInterface;

class UserRepository
{
    public function __construct(private DatabaseInterface $db) {}

    public function find($id)
    {
        return $this->db->select('SELECT * FROM users WHERE id = ?', [$id]);
    }
}

Gotchas and Tips

Pitfalls

  1. DI Container Conflicts

    • Hyperf’s container is incompatible with Laravel’s. Avoid mixing them unless using an adapter.
    • Fix: Use Hyperf’s container exclusively for Hyperf contracts.
  2. Missing Implementations

    • Contracts are interfaces-only; you must provide concrete implementations.
    • Tip: Start with Hyperf’s built-in implementations (e.g., Hyperf\Cache\Redis) or create custom ones.
  3. Version Mismatches

    • Hyperf’s contracts may evolve differently from Laravel’s. Pin versions strictly:
    composer require hyperf/contract:^3.1
    
  4. Lifecycle Hooks Timing

    • Middleware (OnRequest, OnResponse) executes in Hyperf’s HTTP pipeline, not Laravel’s.
    • Tip: Test middleware order in Hyperf’s context, not Laravel’s.
  5. Coroutines in Async Code

    • Hyperf uses coroutines for async tasks. Avoid blocking calls in contracts:
    // Bad: Blocking I/O
    public function fetchData() {
        file_get_contents('https://example.com'); // Blocks coroutine
    }
    // Good: Use Hyperf’s async helpers
    public function fetchData() {
        return yield Co::create(function () {
            return file_get_contents('https://example.com');
        });
    }
    

Debugging

  1. DI Resolution Issues

    • Check if the contract is bound:
    php bin/hyperf container:list
    
    • Ensure the implementation class is autoloaded.
  2. Middleware Not Triggering

    • Verify middleware is registered in config/autoload/middlewares.php.
    • Check Hyperf’s router configuration (config/autoload/routes.php).
  3. Event Dispatcher Not Working

    • Confirm the event listener is registered:
    $this->dispatcher->listen(OrderCreated::class, OrderListener::class);
    

Tips

  1. Start Small

    • Begin with 1–2 critical contracts (e.g., CacheInterface, AuthInterface) before expanding.
  2. Use Hyperf’s Built-ins

    • Leverage Hyperf’s default implementations (e.g., Hyperf\Cache\Redis) to avoid reinventing the wheel.
  3. Adapter Pattern for Laravel

    • Wrap Hyperf contracts in Laravel-compatible facades if needed:
    class LaravelCache implements Illuminate\Contracts\Cache\Store
    {
        public function __construct(private Hyperf\Contract\CacheInterface $cache) {}
    
        public function get($key, $default = null)
        {
            return $this->cache->get($key, $default);
        }
        // ...
    }
    
  4. Testing

    • Mock contracts easily in tests:
    $mockCache = $this->mock(Hyperf\Contract\CacheInterface::class);
    $mockCache->shouldReceive('get')->andReturn('value');
    
  5. Performance

    • Avoid unnecessary abstractions. Use contracts only where modularity or swappability is needed.
  6. Documentation

    • Add PHPDoc to custom implementations for better IDE support:
    /**
     * @implements Hyperf\Contract\CacheInterface
     */
    class RedisCache implements CacheInterface { ... }
    
  7. Hyperf-Specific Features

    • Use Hyperf\Contract\ContextInterface for request-scoped data:
    $context = app(ContextInterface::class);
    $context->set('user_id', 123);
    
  8. Coroutines for Async

    • Use Hyperf\Contract\CoroutineInterface for async workflows:
    use Hyperf\Contract\CoroutineInterface;
    
    class AsyncService
    {
        public function __construct(private CoroutineInterface $coroutine) {}
    
        public function process()
        {
            $this->coroutine->run(function () {
                // Async logic
            });
        }
    }
    
  9. Configuration Overrides

    • Override Hyperf’s default configurations via config/autoload/ files.
  10. Logging

    • Use Hyperf\Contract\LoggerInterface for structured logging:
    use Hyperf\Contract\LoggerInterface;
    
    class MyService
    {
        public function __construct(private LoggerInterface $logger) {}
    
        public function doWork()
        {
            $this->logger->info('Work started');
            // ...
        }
    }
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver