injecting dependencies to presenter

Notice: This thread is very old.
amik
Member | 118
+
0
-

Hi all,
I'm thinking about a coding standard to use inject* methods i.e. in presenters. I've noted that most nette programmers write methods like

public function injectMyService(MyService $myService) {
	$this->myService = $myService;
}

But I find this approach too uncomfortable when presenter has more dependencies (which commonly does).

I started to use another approach:

public function injectFooPresenterDependencies(
	Foo $foo,
	Bar $bar,
	Baz $baz
) {
	$this->foo = $foo;
	$this->bar = $bar;
	$this->baz = $baz;
}

I find this way more comfortable (and more similar to injection via constructor), wondering why programmers use the first one. I just want to discuss what do you think about this approach and if there is some good reason to use the first one.

The only weak spot is that I cannot have single injectDependencies method and call parent::injectDependencies in descendants, so I have to choose unique method name over presenter hierarchy (but still, this is not worse than writing tens of inject methods for complex presenters).

Thanks for opinions :)

Tomáš Votruba
Moderator | 1114
+
0
-

Hi, if you are looking for the most comfortable way, try @inject annotation:

/** @var Foo @inject */
public $foo;
amik
Member | 118
+
0
-

Tomáš Votruba wrote:

Hi, if you are looking for the most comfortable way, try @inject annotation:

/** @var Foo @inject */
public $foo;

Yes, I've noted this possibility, however it was labelled as black magic here
which i quite agree with, it is comfortable, but as far as annotations are not natively supported by PHP, this breaks two main reasons of using DI:
testing:

  • injecting some mock classes to presenters via inject* method is acceptable (and just simpler with my suggestion to use single inject method)
  • injecting to annotated public members lacks PHP type checking and stuff, so it is not very clear way to do DI

encapsulation:

  • @inject-ed variable must be public, which totally breaks encapsulation

This is why I don't like @inject, though it is extremely comfortable.

Last edited by amik (2014-06-16 22:44)