Design Patterns – Does Active Record Violate SRP and OCP?

activerecorddesign-patternsopen-closePHPsingle-responsibility

I have watched the active record classes in our project grow into large, do-it-all classes. When you need anything about a user, for example, you should go to the Person class. While this makes perfect sense when you consider the domain, in reality, the Person class is a mishmash of lots and lots of functionality, which do get modified sometimes as the domain becomes clearer, which means both SRP and OCP are violated.

Is this one of the things that comes with the Active Record pattern, or are we doing it wrong?

Best Answer

The typical use of AR violates these principles. Many developers dump every possible piece of functionality into their models making them fat and cumbersome. The fact that AR makes database interactions an afterthought aids in the misuse.

What you could do is make use of the repository pattern.

Use it to separate your data persistence code from the business logic thus hiding away the details of AR. Then separate your use cases into single responsibility classes. Recently this has been dubbed DCI and it's starting to gain some traction. This will keep your models uber-light and use cases will become more clearly articulated in real classes. Learning to make use of DCI takes some practice but there are a growing number of resources out there and really, once you grok the concept, you shouldn't have much trouble using it. (Don't worry if you make some initial mistakes.)

By taking this tack you wouldn't be tightly bound to AR. You could very easily create interfaces that use the filesystem or any sort of persistence. By making your persistence layer more of an afterthought, you'll have improved your architecture dramatically.