I am starting an application built on zend framework; this application should be able to make use of multiple data sources other than a database; a webservice for example.
I have been reading on how to structure my model so as to allow for this scenario. I have come across various concepts that seem to provide a solution to this (DataMapper Pattern, Service Pattern, Adapter Layer, etc). However, I am still confused on how to put this all together into a reusable and scalable codebase.
I have worked with zend framework before and will normally work with a mysql table. If for example, I have a Users table…I simple have a Users class in my model that contains business logic of the the user domain and a User class extending Zend_Db_Table_Row_Abstract representing a row in the user table.
How best do I organize my model and code base such that i can still call $users->fetchAll() and get a collection of user objects regardless of what my datasource is?
It basically works the same as you did before, just that instead of a
Zend_Db_Table_Gatewayyou use aMy_UserGateway_Whatever, e.g. create an interface first:We dont want Exceptions from the concrete Gateways to appear in the consuming code, so we add the UserGatewayException as a catch all:
Then add a class implementing that interface:
Likewise, if you want to use a Database source, you can write an adapter for the Zend_Db_* classes, e.g.
If you need another Data Provider, make sure they implement that interface, so you can rely on the
findAllmethod to be there. Make your consuming class depend on the interface, e.g.Now, when you create
SomethingUsingUsersyou can easily inject one or the other Gateway into the constructor and your code will work regardless of which Gateway you used:or, for the Webservice: