Zend framework - updating two tables from the same model
I have a model (call it Model_A) that I use to CRUD on a particular table defined by $name var. I also need to update another table (call it Model_B with different $name var) if the first operation in the other model is successful.
I'm trying to update table represented in Model_B from an action in class Model_A. I'm doing this by creating an instance of Model_B inside an action in Model_A. The update action fails fails because it seems to try to write to the table $nam开发者_JS百科e from Model_A, instead of the table $name from the instance of Model_B.
I suppose I could pass the result of the first update back to the controller and then go to the second model, but I'd rather do both updates at the same time.
Apart from an error in my coding, is there any obvious reason why my second update is not finding the right table.. and is this a reasonable aproach for what I'm wanting to do?
Most people think of a Model as coincident with a table class. In fact, they make models extend a base table class. For most simple CRUD type work, this is more or less fine. But as you get into more complex updates across multiple tables, or transaction scripts, you find awkward situations like the one you are asking about.
In fact, a model is not a table. A model is an encapsulation of some logical part of your application's business, not the implementation of storing it in a database.
I worked on the code of Zend_Db_Table quite a bit a few years ago, and when I was writing the manual, I was careful not to refer to table classes as Models.
So you may need to introduce a true Model class layer (which extends no base class), that knows how to do certain application-specific operations against one or more database tables, yet it is not your application's Controller.
Controller -> Model -> Table(s)
This architecture is a great way to avoid repeating code if you have similar business tasks that are called from multiple controllers. It helps to decouple application functions and persistence details from your Controllers, which has benefits in code maintenance, testability, encapsulation, etc.
Check out the free mini-book Domain-Driven Design Quickly (based on Eric Evans books), or the chapter "Magic Beans" in my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.
Zend_Db_Table has an important property called "RefrenceMap" in which you define logic how your one table links to the other check the below url to read further http://framework.zend.com/manual/en/zend.db.table.relationships.html
精彩评论