# Contracts Package Specification ## Overview The Contracts package defines the core interfaces and contracts that form the foundation of the framework. These contracts ensure consistency and interoperability between components while enabling loose coupling and dependency injection. > **Related Documentation** > - See [Laravel Compatibility Roadmap](laravel_compatibility_roadmap.md) for implementation status > - See [Foundation Integration Guide](foundation_integration_guide.md) for integration patterns > - See [Testing Guide](testing_guide.md) for testing approaches > - See [Getting Started Guide](getting_started.md) for development setup ## Core Contracts ### 1. Container Contracts ```dart /// Core container interface abstract class ContainerContract { /// Resolves a type from the container T make([dynamic context]); /// Binds a type to the container void bind(T Function(ContainerContract) concrete); /// Binds a singleton to the container void singleton(T Function(ContainerContract) concrete); /// Checks if a type is bound bool has(); /// Tags implementations for grouped resolution void tag(List implementations, String tag); /// Gets all implementations with a tag List tagged(String tag); /// Adds a contextual binding void addContextualBinding(Type concrete, Type abstract, dynamic implementation); /// Creates a new child container ContainerContract createChild(); } /// Interface for contextual binding abstract class ContextualBindingBuilder { /// Specifies the type needed in this context ContextualNeedsBuilder needs(); } /// Interface for contextual needs abstract class ContextualNeedsBuilder { /// Specifies what to give for this need void give(dynamic implementation); } /// Interface for service providers abstract class ServiceProviderContract { /// Registers services with the container void register(); /// Bootstraps any services Future boot(); /// Gets provided services List provides(); /// Whether provider is deferred bool get isDeferred => false; } ``` ### 2. Event Contracts ```dart /// Core event dispatcher interface abstract class EventDispatcherContract { /// Registers an event listener void listen(void Function(T event) listener); /// Dispatches an event Future dispatch(T event); /// Registers an event subscriber void subscribe(EventSubscriber subscriber); /// Dispatches an event after database commit Future dispatchAfterCommit(T event); /// Gets registered listeners List getListeners(Type event); } /// Interface for event subscribers abstract class EventSubscriber { /// Gets events to subscribe to Map subscribe(); } /// Interface for queueable events abstract class ShouldQueue { /// Gets the queue to use String get queue => 'default'; /// Gets the delay before processing Duration? get delay => null; /// Gets the number of tries int get tries => 1; } /// Interface for broadcastable events abstract class ShouldBroadcast { /// Gets channels to broadcast on List broadcastOn(); /// Gets event name for broadcasting String broadcastAs() => runtimeType.toString(); /// Gets broadcast data Map get broadcastWith => {}; } ``` ### 3. Queue Contracts ```dart /// Core queue interface abstract class QueueContract { /// Pushes a job onto the queue Future push(dynamic job, [String? queue]); /// Pushes a job with delay Future later(Duration delay, dynamic job, [String? queue]); /// Gets next job from queue Future pop([String? queue]); /// Creates a job batch Batch batch(List jobs); /// Gets a queue connection QueueConnection connection([String? name]); } /// Interface for queue jobs abstract class Job { /// Unique job ID String get id; /// Job payload Map get payload; /// Number of attempts int get attempts; /// Maximum tries int get tries => 1; /// Timeout in seconds int get timeout => 60; /// Executes the job Future handle(); /// Handles job failure Future failed([Exception? exception]); } /// Interface for job batches abstract class Batch { /// Batch ID String get id; /// Jobs in batch List get jobs; /// Adds jobs to batch void add(List jobs); /// Dispatches the batch Future dispatch(); } ``` ### 4. Bus Contracts ```dart /// Core command bus interface abstract class CommandBusContract { /// Dispatches a command Future dispatch(Command command); /// Dispatches a command now Future dispatchNow(Command command); /// Dispatches a command to queue Future dispatchToQueue(Command command); /// Creates a command batch PendingBatch batch(List commands); /// Creates a command chain PendingChain chain(List commands); } /// Interface for commands abstract class Command { /// Gets command handler Type get handler; } /// Interface for command handlers abstract class Handler { /// Handles the command Future handle(T command); } /// Interface for command batches abstract class PendingBatch { /// Dispatches the batch Future dispatch(); /// Allows failures PendingBatch allowFailures(); } ``` ### 5. Pipeline Contracts ```dart /// Core pipeline interface abstract class PipelineContract { /// Sends value through pipeline PipelineContract send(T passable); /// Sets the pipes PipelineContract through(List> pipes); /// Processes the pipeline Future then(Future Function(T) destination); } /// Interface for pipes abstract class PipeContract { /// Handles the passable Future handle(T passable, Function next); } /// Interface for pipeline hub abstract class PipelineHubContract { /// Gets a pipeline PipelineContract pipeline(String name); /// Sets default pipes void defaults(List pipes); } ``` ## Usage Examples ### Container Usage ```dart // Register service provider class AppServiceProvider implements ServiceProviderContract { @override void register() { container.bind((c) => UserService( c.make(), c.make() )); } @override Future boot() async { // Bootstrap services } } ``` ### Event Handling ```dart // Define event class OrderShipped implements ShouldQueue, ShouldBroadcast { final Order order; @override List broadcastOn() => ['orders.${order.id}']; @override String get queue => 'notifications'; } // Handle event dispatcher.listen((event) async { await notifyCustomer(event.order); }); ``` ### Command Bus Usage ```dart // Define command class CreateOrder implements Command { final String customerId; final List products; @override Type get handler => CreateOrderHandler; } // Handle command class CreateOrderHandler implements Handler { @override Future handle(CreateOrder command) async { // Create order } } // Dispatch command var order = await bus.dispatch(CreateOrder( customerId: '123', products: ['abc', 'xyz'] )); ``` ## Testing ```dart void main() { group('Event Dispatcher', () { test('dispatches after commit', () async { var dispatcher = MockEventDispatcher(); var db = MockDatabase(); await db.transaction((tx) async { await dispatcher.dispatchAfterCommit(OrderShipped(order)); }); verify(() => dispatcher.dispatch(any())).called(1); }); }); group('Command Bus', () { test('handles command batch', () async { var bus = MockCommandBus(); await bus.batch([ CreateOrder(...), UpdateInventory(...) ]).dispatch(); verify(() => bus.dispatchNow(any())).called(2); }); }); } ``` ## Contract Guidelines 1. **Keep Contracts Minimal** ```dart // Good: Focused contract abstract class Cache { Future get(String key); Future put(String key, T value); } // Bad: Too many responsibilities abstract class Cache { Future get(String key); Future put(String key, T value); void clearMemory(); void optimizeStorage(); void defragment(); } ``` 2. **Use Type Parameters** ```dart // Good: Type safe abstract class Repository { Future find(String id); Future save(T entity); } // Bad: Dynamic typing abstract class Repository { Future find(String id); Future save(dynamic entity); } ``` 3. **Document Contracts** ```dart /// Contract for caching implementations. /// /// Implementations must: /// - Handle serialization /// - Be thread-safe /// - Support TTL abstract class Cache { /// Gets a value from cache. /// /// Returns null if not found. /// Throws [CacheException] on error. Future get(String key); } ``` ## Next Steps 1. Implement core contracts 2. Add integration tests 3. Document Laravel compatibility 4. Add migration guides 5. Create examples 6. Write tests Would you like me to enhance any other package specifications? ## Development Guidelines ### 1. Getting Started Before implementing contracts: 1. Review [Getting Started Guide](getting_started.md) 2. Check [Laravel Compatibility Roadmap](laravel_compatibility_roadmap.md) 3. Follow [Testing Guide](testing_guide.md) 4. Use [Foundation Integration Guide](foundation_integration_guide.md) ### 2. Implementation Process For each contract: 1. Write tests following [Testing Guide](testing_guide.md) 2. Implement following Laravel patterns 3. Document following [Getting Started Guide](getting_started.md#documentation) 4. Integrate following [Foundation Integration Guide](foundation_integration_guide.md) ### 3. Quality Requirements All implementations must: 1. Pass all tests (see [Testing Guide](testing_guide.md)) 2. Meet Laravel compatibility requirements 3. Follow integration patterns (see [Foundation Integration Guide](foundation_integration_guide.md)) ### 4. Integration Considerations When implementing contracts: 1. Follow patterns in [Foundation Integration Guide](foundation_integration_guide.md) 2. Ensure Laravel compatibility per [Laravel Compatibility Roadmap](laravel_compatibility_roadmap.md) 3. Use testing approaches from [Testing Guide](testing_guide.md) 4. Follow development setup in [Getting Started Guide](getting_started.md)