· 8 years ago · Jul 02, 2018, 11:14 AM
1A table is an object holding an connection ($sql variable) to interact with Database.
2A feature is used to hook into table events (select, insert...) to modify query, logic.
3
4A table will have a feature set.
5A feature will link to 1 table.
6
7We will only focus in masterSlaveFeature, which is used to change connection ($sql variable) of the table it links to. This feature will hold a connection (slave connection) will used to switch table master connection to slave connection if needed. Inside the connecion variable, there's an IMPORTANT value is TABLE_NAME, pay attention to this data).
8
9
10Let look at the code
111. When we call a Table, Zend Service Container will create a table object by a Factory
12Enrich\Core\Services\CommonTableAbstractFactory::createServiceWithName line 61-64
132. It calls get masterSlaveFeature(): if masterSlaveFeature doesn't exists, create new, otherwise use the existing one.
14
15When we call Table select function at
16/Zend/Db/TableGateway/AbstractTableGateway::select
17
183. It will call initialize function if the table has not been init yet.
19In this init function, we should take care the code
20$this->featureSet->setTableGateway($this) (line 97).
21
22
23and also MasterSlaveFeature::postInitialize event (line 60)
24
25This code will link all the features inside featureSet to the current table gateway. (Please pay attention the MasterSlaveFeature only)
26
274. Then select will call selectWith -> executeSelect
285. inside executeSelect, a PRE_SELECT and POST_SELECT event dispatched, MasterSlaveFeature hook to that event with the code
29In MasterSlaveFeature, 2 hooks are
30preSelect
31postSelect
32
33In 2 these hooks, it changes Table Connection by its connection (!!!)
34$this->tableGateway->sql = $this->slaveSql
35$this->tableGateway->sql = $this->masterSql
36
37
38
39
40ENOUGH BUNNY HOLE, LET'S GET TO THE EXAMPLE
41- We get table Product
42 - A new Table object created
43 - A new Feature object created
44 - Table link to feature, feature link to table
45 - Call postInitialize (see 3):
46 - Table has $sql var has TABLE_NAME = 'Product'
47 - Feature has masterConnection (reference to table Product connection) and its own slaveConnection
48- Query some product, the event hooks run, changed table connection (see 5)
49
50
51- We get table User
52 - A new User object created
53 - Use existing Feature object
54 - Table link to feature, feature link to table
55 - Call postInitialize (see 3):
56 - Table has $sql var has TABLE_NAME = 'User'
57 - Feature has masterConnection (reference to table User connection!!!) and its own slaveConnection
58- Query some product, the event hooks run, changed table connection (see 5)
59
60
61- We get back table Product
62 - Use existing Product Table object
63 - Use existing Feature object
64 - postInitialize not called again
65At this time the feature is holding its masterConnection and slaveConnection link to User table ====> BOOMMM