How to solve the problem of composing a Controller class in PHP, which should be:
- easily testable by employing Dependency Injection,
- provide shared objects for end programmer
- provide a way to load new user libraries
Look down, for controller instantiation with a Dependency injection framework
The problem is, that derived Controllers may use whatever resources the programmer wants to (eg. the framework provides). How to create a unified access to shared resources (DB, User, Storage, Cache, Helpers), user defined Classes or another libraries?
Elegant solution?
There are several possible solutions to my problem, but neither one looks to be a elegant
- Try to pass all shared objects by constructor? (may create constructor even with 10 placeholders)
- Create getters, settters? (bloated code)
$controller->setApplication($app)
- Apply singletons on shared resources?
User::getInstance()
orDatabase::getInstance()
- Use Dependency Injection container as a singleton for object sharing inside the controller?
- provide one global application singleton as a factory? (this one looks very used in php frameworks, hovewer it goes strongly against DI principles and Demeter's law)
I understand, that creating strongly coupled classes is discouraged and banished for :), however I don't know how this paradigm applies to a starting point for other programmers (a Controller class), in which they should be able to access shared resources provided to the MVC architecture. I believe, that breaking up the controller class into smaller classes would somehow destroy the practical meaning of MVC.
Dependency Injection Framework
DI Framework looks like a viable choice. However the problem still persists. A class like Controller does not reside in the Application layer, but in the RequestHandler/Response layer.
How should this layer instantiate the controller?
- pass the DI injector into this layer?
- DI Framework as a singleton?
- put isolated DI framework config only for this layer and create separate DI injector instance?