20

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() or Database::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?
Juraj Blahunka
  • 17,913
  • 6
  • 34
  • 52
  • Are you looking for a PHP-specific answer? – G-Wiz Feb 05 '10 at 23:59
  • Yes I forgot to say, that the language is PHP, but I think the solution should be language independent – Juraj Blahunka Feb 06 '10 at 00:22
  • Related: http://stackoverflow.com/questions/1967548/best-way-to-access-global-objects-like-database-or-log-from-classes-and-scripts and http://stackoverflow.com/questions/1812472/in-a-php-project-how-do-you-organize-and-access-your-helper-objects – philfreo Feb 06 '10 at 01:00
  • I have read them before asking. Both suggest using Dependency Injection, but DI requires the `parent` to ask for `children`, which are injected. The so called 'parent' knows what he is going to do and therefore knows what to ask. I'm stuck in the controller implementation.. Controller should be flexible, so the end programmer can do everything he wants in the application logic. Is it best to inject totally every object possible? Provide containers? But this would break Demeter's law... – Juraj Blahunka Feb 06 '10 at 01:12
  • Maybe you can look into this little DI library. Very simple to use and testable http://gabordemooij.com/harbour/ – Robert Cabri Feb 08 '10 at 12:04

5 Answers5

3

Are you developing a framework yourself? If not, your question does not apply, because you have to choose from already existing frameworks and their existing solutions. In this case your question must be reformulated like "how do I do unit testing/dependency injection in framework X".

If you are developing a framework on you own, you should check first how already existing ones approach this issue. And you must also elaborate your own requirements, and then just go with the simplest possible solution. Without requirements, your question is purely aesthetic and argumentative.

In my humble opinion the simplest solution is to have public properties which initialize to defaults provided by your framework, otherwise you can inject your mocks here. (This equals to your getters/setters solution, but without the mentioned bloat. You do not always need getters and setters.) Optionally, if you really need it, you may provide a constructor to initialize those in one call (as you suggested).

Singletons are an elegant solution, but again, you must ask yourself, is it applicable in your case? If you have to have different instances of the same type of object in your application, you can't go with it (e.g. if you wish to mock a class only in half of your app).

Of course it is really awesome to have all the options. You can have getters/setter, constructors, and when initialization is omitted, default are taken from a singleton factory. But having too many options when not needed, is not awesome, it is disturbing as the programmer has to figure out which convention, option and pattern to use. I definitely do not want to make dozens of design decisions just to get a simple CRUD running.

If you look at other frameworks you will see that there is no silver bullet. Often a single framework utilizes different techniques depending on the context. In controllers, DI is a really straightforward thing, look at CakePHP's $helpers, $components variables, which instruct to inject appropriate variables into the controller class. For the application itself a singleton is still a good thing, as there is always just a single application. Properties less often changed/mocked are injected utilizing public properties. In case of an MVC, subclassing is perfectly viable option as well: just as AppController, AppView, AppModel in CakePHP. They are inserted into the class hierarchy between the frameworks's and all your particular Controller, View and Model classes. This way you have a single point to declare globals for your main type of classes.

In Java, because of dynamic class loaders and reflection, you have even much more options to choose from. But on the other hand, you have to support much more requirements as well: parallel requests, shared objects and states between worker threads, distributed app servers etc.

You can only answer the question what is right for you, if you know what you need in the first place. But actually, why do you write just another new framework anyway?

Cave Johnson
  • 6,499
  • 5
  • 38
  • 57
sibidiba
  • 6,270
  • 7
  • 40
  • 50
  • Yes, I'm building, trying out a simple component based framework, I needed the exact push, your answer gave me.. Also, as I stated before, a lot of frameworks solve these by utilizing Singletons, but I want to evade global state as much as possible (components should be easily replaceable). Will upvote next day (ran out of votes :)). Thank you for your time – Juraj Blahunka Feb 14 '10 at 21:01
  • "Singletons are an Elegant Solution"?! Singletons are not at all elegant and they hide class dependencies, many consider them an anti-pattern. – Yisrael Dov May 22 '17 at 09:42
1

Singletons are frowned upon when Dependency Injection is viable (and I have yet to find a case where a Singleton was necessary).

More than likely you will have control of instantiation of controllers, so you can get away with the mentioned $controller->setApplication($application), but if necessary you can use static methods and variables (which are far less harmful to the orthogonality of an application than Singletons); namely Controller::setApplication(), and access the static variables through the instance methods.

eg:

// defining the Application within the controller -- more than likely in the bootstrap
$application = new Application();
Controller::setApplication($application);

// somewhere within the Controller class definition
public function setContentType($contentType)
{
    self::$application->setContentType($contentType);
}

I have made of a habit of separating static and instance properties and methods (where necessary, and still grouping properties at the top of the class definition). I feel that this is less unwieldy than having Singletons, as the classes still remain quite compact.

Adrian
  • 1,392
  • 9
  • 9
  • 1
    This doesn't look like a solution, for which test writing would be easy.. The `::setApplication` will create a global state for all Controllers and I don't believe this is the way to go.. – Juraj Blahunka Feb 06 '10 at 16:48
1

How about refactoring?

Granted that was not one of your options, but you state the code is a largely coupled class. Why not take this time and effort to refactor it to more modular, testable components?

Finglas
  • 15,518
  • 10
  • 56
  • 89
  • Good point, however I don't know whether it's good idea, as by breaking up the Controller class, the MVC pattern would shatter.. – Juraj Blahunka Feb 11 '10 at 19:54
  • You'd still have a controller as is, but the controller would be refactored so that the internals of that class are changed. The public interface to your controller should remain unchanged, it just the code internally will be split up. Granted this is speculation on what your code looks like, but that's what I'd do. – Finglas Feb 11 '10 at 20:45
  • Can you point me to some studies or blogs, where this is discussed? – Juraj Blahunka Feb 12 '10 at 07:10
  • Check out the Single Responsiblity Principle (Part of SOLID). To summarise, a class should do one thing and one thing well. Not multiple jobs, which is what your controller sounds like it's doing now. – Finglas Feb 13 '10 at 10:46
  • I still get back to using DI, passing loader objects as param, which can load other libs for end user (easy to mock and test) – Juraj Blahunka Feb 14 '10 at 12:03
  • D.I is a given for testable code, whether you use constructor injection, a framework and so on it matters not. – Finglas Feb 14 '10 at 12:19
1

As far as I understand, the Application class of yours should be the dispatcher. If so, I would rather use the controller constructor to pass an instance of the Application, so the controller would know who's invoking it. At later point if you want to have a different Application instance depending on whether the code is invoked from within CLI, you can have an ApplicationInterface which the Application\Http and Application\Cli would implement and everything would be easy to maintain.

You could also implement some factory pattern to get a nice implementation of the DI. For example, check the createThroughReflection method here: https://github.com/troelskn/bucket/blob/master/lib/bucket.inc.php

I hope this makes sense.

Regards, Nick

Nikola Petkanski
  • 4,724
  • 1
  • 33
  • 41
1

You could also use a ControllerFatory in which you would give to your Application or Router/Dispatcher

Sou you could call $controllerFactory->createController($name);

Your Application would have no idea how to create your controllers the Factory would. Since you ca inject your own ControllerFactory in to your DI container you can manage all dependencies you want depending on the controller.

class ControllerFactory {
    public function __construct(EvenDispatcher $dispatcher,
                                Request $request,
                                ResponseFactory $responseFactory, 
                                ModelFactory $modelFactory, 
                                FormFactory $formFactory) {
        ...
    }

    public function createController($name = 'Default') {
        switch ($name) {
            case 'User':
              return new UserController($dispatcher, 
                                        $request, 
                                        $responseFactory->createResponse('Html'), 
                                        $modelFactory->createModel('User'),
                                        $formFactory->createForm('User'),...);

              break;
            case 'Ajax':
              return new AjaxController($dispatcher, 
                                        $request, 
                                        $responseFactory->createResponse('Json'), 
                                        $modelFactory->createModel('User'));
              break;
            default:
                 return new DefaultController($dispatcher, $request, $responseFactory->createResponse('Html'));
        }
    }

} 

So you just need to add this factory in your DI container and pass it to your Application. Whenever you need a new controller you add it to the factory and if new dependencies are required you give them to the factory through your DI container.

class App {
    public function __construct(Router $router,Request $request, ControllerFactory $cf, ... ) {
      ...
    }

    public function execute() {
        $controllerName = $this->router->getMatchedController();
        $actionName $this->router->getMatchedAction();

        $controller = $cf->createController($controllerName);

        if(is_callable($controller, $actionName)) {
            $response = $controller->$action(request);
            $response->send();     
        }
    }
}

This is not production code, I haven't tested, but this is how you decouple your controllers from your application. Notice here though that there is one bad coupling here because my controller return's a response and I execute the response in the App. But like I said this is just a small example.

It is usually a good idea to pass factories for Models, Forms, and Controllers to their respective parents, because you will end up loading all your object Graph at bootstrap time wich is really bad and memory consuming.

I know this answer was already approved, but it's my 2 cents on the subject

There is a good article on the subject

http://miller.limethinking.co.uk/2011/07/07/dependency-injection-moving-from-basics-to-container/

inkubux
  • 236
  • 2
  • 11