PHP specification pattern that allows transformation to sql
I'm trying to find out what the best way would be to have a specification pattern in PHP where the specifications could (optionally) by transform开发者_JAVA百科ed to PHP.
I am exploring some new directions and am testing how well they would work. Code and ideas are still very unclear in my mind.
Minimal interfaces would be like these:
interface IRepository {
public function get(ISpecification $specification);
}
interface ISpecification {
public function isSatisfiedBy($candidate);
}
If the repository hides a sql database the specification would need to transform to sql. Adding a ->toSQL() method seems ad hoc. A class that translates the specifications is also an option but it seems like a lot of overhead to finally generate the sql.
Ideas appreciated.
Quoting from POEAA (pg.324):
Under the covers, Repository combines Metadata Mapping (329) with a Query Object (316) to automatically generate SQL code from the criteria. Whether the criteria know how to add themselves to a query, the Query Object (316) knows how to incorporate criteria objects, or the Metadata Mapping (306) itself controls the interaction is an implementation detail.
The criteria in this descriptions are of course your Specification pattern. I'd say your suggested approach to use a toSQL
method on the criteria objects is fine when the application is relatively small. Like you already said, going the other routes is more difficult, but it also provides greater flexibility and decoupling. In the end, only you can decide.
精彩评论