Reputation: 846
First of all I'm relatively new in ios and have no any experience using mobile 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.
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)
}
}
Upvotes: 8
Views: 2079
Reputation: 16011
Adding an abstraction layer over the top of database APIs is pretty common. A lot of other developers have wrapped Realm in their own classes in order to hide the API from their business logic code.
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.
Upvotes: 8
Reputation: 1996
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. 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
}
}
Upvotes: 1