cqrs: The Command and Query Responsibility Segregation

cqrs

License Swift Compatibility Platform Compatibility CI CodeCov

描述

cqrs 是 Swift 中命令和查询职责分离的实现。

用法

  1. ICommandIQuery 包含供适当处理程序使用的数据。

分别创建符合 ICommand 的命令实例或符合 IQuery 的查询实例

import CQRS

final class ExampleCommand: ICommand {
  // MARK: Properties
 
  let value: Int
 
  // MARK: Initialization
  
  init(value: Int) {
    self.value = value
  }
}
import CQRS

final class ExampleQuery: IQueue {
    typealias Result = Int

    // MARK: Properties

    let value: Int

    // MARK: Initialization

    init(value: Int) {
        self.value = value
    }
}
  1. 命令处理程序或查询处理程序包含命令或查询的执行逻辑。

分别创建符合 ICommandHandler 的命令处理程序实例或符合 IQueryHandler 的查询处理程序实例

import CQRS

final class ExampleCommandHandler: ICommandHandler {
  typealias Command = ExampleCommand

  // MARK: ICommandHandler

  func execute(command: Command) throws {
    // write the execution logic here
  }
}
import CQRS

final class ExampleQueryHandler: IQueryHandler {
    typealias Query = ExampleQuery

    // MARK: IQueryHandler

    func execute(query: Query) throws -> Query.Result {
        // write the execution logic here
    }
}
  1. 在容器中注册你的处理程序实现
import CQRS

let container = DependencyContainer()
container.register { ExampleCommandHandler() }
import CQRS

let container = DependencyContainer()
container.register { ExampleQueryHandler() }
  1. 使用创建的容器创建 CommandDispatcherQueryDispatcher 的实例,像这样
import CQRS

let commandDispatcher = CommandDispatcher(container: container)
import CQRS

let commandDispatcher = QueryDispatcher(container: container)
  1. commandDispatcherqueryDispatcher 上执行你的命令
let command = ExampleCommand()

do {
  try commandDispatcher.execute(command: command)
} catch {
  // Handle an error.
}
let query = ExampleCommand()

do {
  let result = try queryDispatcher.execute(query: query)
} catch {
  // Handle an error.
}

要求

安装

Swift Package Manager

Swift Package Manager 是一个自动化 Swift 代码分发的工具,并已集成到 swift 编译器中。它还处于早期开发阶段,但 cqrs 确实支持在受支持的平台上使用它。

一旦你设置好你的 Swift 包,添加 cqrs 作为依赖项就像将其添加到你的 Package.swiftdependencies 值一样简单。

dependencies: [
    .package(url: "https://github.com/space-code/cqrs.git", .upToNextMajor(from: "1.0.1"))
]

交流

贡献

搭建开发环境

make bootstrap

请随时帮助改进这个项目!如果你看到任何可以改进的地方或想要新功能,请打开一个 issue 或发送一个 Pull Request!

作者

Nikita Vasilev, nv3212@gmail.com

许可证

cqrs 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。