Inversion of ControlOne Definition:The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code. For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:
What we've done here is create a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:
Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We're injecting the TextEditor with the dependency. This is just a simple example, there's a good series of articles by Simone Busoli that explains it in greater detail. << Like in this example with TextEditor: if you have only one SpellChecker maybe it is not really necessary to use IoC ? Unless you need to write unit tests or something ... Do not overuse this pattern >> Another One:Inversion of Control is what you get when you program callbacks, e.g. like a gui program. For example, in an old school menu, you might have:
thereby controlling the flow of user interaction. In a GUI program or somesuch, instead we say
So now control is inverted... instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database. Basically, anything with an event loop, callbacks, or execute triggers falls into this category. Another OneWhat is Inversion of Control? If you follow these simple two steps, you have done inversion of control:
There are several techniques possible for each of these steps based on the technology/language you are using for your implementation. -- The inversion part of the Inversion of Control (IoC) is the confusing thing; because inversion is the relative term. The best way to understand IoC is to forget about that word! -- Examples
The Last Word:
------------------------------------- Drupal makes use of the inversion of control design pattern, in which modular functionality is called by the framework at the appropriate time. These opportunities for modules to do their thing are called hooks. |