[英]Should I use repository for Realm(ios)
First of all I'm relatively new in ios and have no any experience using mobile dbs. 首先,我在ios中相对较新,没有任何使用移动dbs的经验。
Wanted to integrate into my app Realm(swift) and wonder if it make sense to have service layer and repository separated or everything just include into the service. 想要集成到我的应用程序Realm(swift),并想知道将服务层和存储库分开或者所有内容都包含在服务中是否有意义。
Some example to have a good view. 一些例子有一个很好的观点。
class UserService {
var userRepository: UserRepository!
func findById(userId: String) -> User? {
return userRepository.findById(userId: userId)
}
}
class UserRepository {
private let realm = try! Realm()
func findById(userId: String) -> User? {
return realm.object(ofType: User.self, forPrimaryKey: userId)
}
}
Adding an abstraction layer over the top of database APIs is pretty common. 在数据库API顶部添加抽象层非常常见。 A lot of other developers have wrapped Realm in their own classes in order to hide the API from their business logic code.
许多其他开发人员已经将Realm包装在他们自己的类中,以便将API隐藏在他们的业务逻辑代码中。
There's a couple of considerations in which to be aware: 需要注意几个方面的考虑因素:
As long as the new database you'd be moving to consists of managing objects as well (ie Core Data), converting from one database to another isn't usually a lot of work. 只要您要移动的新数据库也包含管理对象(即核心数据),从一个数据库转换到另一个数据库通常不是很多工作。 As such, I'd recommend avoiding unnecessary work until the time when it becomes necessary.
因此,我建议在必要时避免不必要的工作。
Disclaimer: I work for Realm, but this is my opinion as someone who's shipped personal apps using Core Data, raw SQLite and Realm in the past. 免责声明:我为Realm工作,但这是我的观点,因为过去曾使用Core Data,原始SQLite和Realm发布个人应用程序。
You can use extensions to add your fetching methods. 您可以使用扩展来添加提取方法。 You add Object subclasses for each entity in your database and then add extensions to each for these methods when needed.
您可以为数据库中的每个实体添加Object子类,然后在需要时为这些方法添加扩展。 Example:
例:
import RealmSwift
// Dog model
class Dog: Object {
dynamic var name = ""
dynamic var owner: Person? // Properties can be optional
}
The for your fetching methods: 对于你的提取方法:
extension Dog {
class func fetch(with name: String) -> Dog? {
return try! Realm().objects(Dog.self).filter("name == %@", name).first
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.