ZF Controller Actions - DI

Hi,

I came across this snippet of code today:


public function loginAction() {
  $request = $this->getRequest();

  if ($request->isPost()) {
    $users = new Model_Users(); // <- ?

    if ($user = $users->login($request->getParam('email'), $request->getParam('password')) {
      //....
    }
  }
}

This piece of code is instantiating a Users object within the method. This would make it harder to customize later on. But because the nature of controllers, an obstacle I can think of is “how to figure out all the objects I will need BEFORE (dynamically) calling the action method”.

What do you guys think? What are some of the ways you have tackled this situation?

EDIT:

Is the idea to use as much dependency injection as possible but only if it’s possible?

This piece of code is instantiating a Users object within the method
Yes, but inside IF block (= not always).

how to figure out all the objects I will need BEFORE (dynamically) calling the action method
Why do you need that?

What does it matter if it’s inside the if statement or not? It’s not following dependency injection if the statement evaluated to true.

And for your 2nd question:
If I were to be religious of DI then I would need to know the parameters ahead of time ie:


public function loginAction(Models_Users $users, Foo $foo, Bar $bar) {
  //...
}

In this case you need to pass instances. Why, if you sometimes do not use them?

Hi…

Pass a factory instead for the class instead to achieve DI. Then the “new” call is replaced by a factory method and you call that conditionally instead. The factory is super lightweight, so instantiating it has little cost.

I don’t see why you can’t instantiate Model_Users though. What is the start up cost? I would have thought that if you needed to write to something you would probably need a page to display the results or other confirmations anyway.

I sense that something is misfactored.

yours, Marcus

I did not write this code, I just found it and thought it was a good way of understanding DI in a different way.

By passing a factory, it would only fix for the users model. What if I wanted to use an additional model? If we keep the open-closed principle in mind, then that wouldn’t work.

What I’m trying to understand is when it’s ok to use DI and when to instantiate an object within the method without DI. After looking into the ZF source, I noticed that they don’t ALWAYS use DI. So how does one need to think for this type of scenario?