Dependency Injection best practices

Notice: This thread is very old.
Ajax
Member | 59
+
0
-

I'm lost in dependency injection. I read lot of tutorials and forums, but I'm still lost. Here is my (simplified) situation:

I have class File in model (see comments):

namespace App\Model\Files;  //Is it OK to have it in model???

use Nette;


class File extends Nette\Object //Is it OK to inherit from Nette\Object????
{
	public function open($path, $rw = 'r')
	{
		...
	}

	public function close()
	{
		...
	}

	public function getFileContent(){
		...
	}
}

Now, I need to read data from file in presenter (???) and gave them into view. Question is, how to do it? Or should I go in different way?
Thanks!

Ajax
Member | 59
+
0
-

Oh common.. Minus one and no answer? Because of what? Is it explained elsewhere? So, tell me, where? I read (besides of tones of other tutorials and forum posts) this: DI usage. Here is written use constructor (impossible), by setter (impossible) and @inject method. But when I use /** @var \App\Model\Files\File @inject */, Nette says Service of type App\Model\Files\File not found. But I don't want it as service. If I understand it right, when I'll have 200 classes, I'll have to set 200 services? Is it right approach? I don't know, so, I asked and got –1 and no answer. :(

And just one note. Many times, Nette doc, forum posts and other tutorials says contradictory things. For example, I found post with code $this->context->parameters['debugMode'], another tutorial says \Nette\Environment::isProduction(), which is deprecated and another says don't use context. So, Nette greenhorn is confused. Everyone says “Nette has great forum”. But you cant asks basics? :(

looky
Member | 99
+
+1
-

If you want to use DI, you have to have services. System container (the thing that actually handles DI) looks in it's list of services to provide you with the one you requested.

If you don't want to have it as a service, you can still create the object using new.

I admit, I don't fully understand your example, but if you don't want 200 services registered in config, maybe use a factory for them? Register one service (something like FileFactory) with some create method (probably with $path argument) which would create you a new File object, autowire it in your presenter, and call it like $file = $this->fileFactory->create(‘path/to/your/file’);

Last edited by looky (2014-06-26 15:17)

Ajax
Member | 59
+
0
-

Thank you very much for your answer.

Maybe, I did not explain it clear, In case, when I need to have class for xml file, csv file, etc… What is right approach? Use this factory to return right class according parameter? Something like

	$file = $this->fileFactory->create(‘path/to/your/file’, 'xml');

Or is it not right approach?

Thanks…