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.
Installation Require the package via Composer:
composer require hyperf/contract
No additional configuration is needed—it provides only interfaces.
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
}
}
Where to Look First
src/Contract directory for available interfaces.Hyperf\Contract\) to discover relevant contracts.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
);
@Inject to auto-wire dependencies:
use Hyperf\Di\Annotation\Inject;
class OrderService
{
#[Inject]
public CacheInterface $cache;
}
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,
],
];
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,
],
];
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));
}
}
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');
}
}
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]);
}
}
DI Container Conflicts
Missing Implementations
Hyperf\Cache\Redis) or create custom ones.Version Mismatches
composer require hyperf/contract:^3.1
Lifecycle Hooks Timing
OnRequest, OnResponse) executes in Hyperf’s HTTP pipeline, not Laravel’s.Coroutines in Async Code
// 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');
});
}
DI Resolution Issues
php bin/hyperf container:list
Middleware Not Triggering
config/autoload/middlewares.php.config/autoload/routes.php).Event Dispatcher Not Working
$this->dispatcher->listen(OrderCreated::class, OrderListener::class);
Start Small
CacheInterface, AuthInterface) before expanding.Use Hyperf’s Built-ins
Hyperf\Cache\Redis) to avoid reinventing the wheel.Adapter Pattern for Laravel
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);
}
// ...
}
Testing
$mockCache = $this->mock(Hyperf\Contract\CacheInterface::class);
$mockCache->shouldReceive('get')->andReturn('value');
Performance
Documentation
/**
* @implements Hyperf\Contract\CacheInterface
*/
class RedisCache implements CacheInterface { ... }
Hyperf-Specific Features
Hyperf\Contract\ContextInterface for request-scoped data:$context = app(ContextInterface::class);
$context->set('user_id', 123);
Coroutines for Async
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
});
}
}
Configuration Overrides
config/autoload/ files.Logging
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');
// ...
}
}
How can I help you explore Laravel packages today?