Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

What is the best between:

$dispatcher = new Dispatcher($request);
$dispatcher->dispatch();

and

$dispatcher = new Dispatcher();
$dispatcher->dispatch($request);

or even

Dispatcher::dispatch($request);

Knowing that only one method of this class uses the $request instance.

I naturally tend to the last solution because the class have no other states, but by I feel that it may not be the best OOP solution.

share|improve this question

closed as primarily opinion-based by Euphoric, Bart van Ingen Schenau, GlenH7, gnat, Kilian Foth Aug 21 at 15:29

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

    
On-Topic: If I was you, I'd go for the first way so that I could call that function anywhere, but I guess second and third ways will only allow them to be called where the class instances. Off-topic: Nice blog, yet it needs more articles xD. –  Hassan Althaf Aug 20 at 12:07
2  
I do not see how this is an example of dependency injection: the request is just an argument to the dispatch() method or function, or do requests implement some particular functionality? Anyway, in you scenario I would rather imagine a dispatcher implementation to be injected into some containing object. –  Giorgio Aug 20 at 14:53
    
So if I understand, it's not necessary to inject a object in a class constructor if this class only uses it in only one method even if it's an object which does something? –  gaetanm Aug 20 at 21:47
    
Maybe this belongs on CodeReview instead? –  GlenPeterson Aug 21 at 15:22
    
@Giorgio Yes the request is an object having methods like $request->getController() or $request->getAction. –  gaetanm Aug 24 at 11:45

1 Answer 1

up vote 2 down vote accepted

The best option would be the second one. This allows you to create stateless objects and also change the implementation in the future. The third one won't allow polymorphism and the first one will be statefull.

share|improve this answer
    
In an article about dependency injection, I've read: "An A class depends on another class B when class A has an attribute of type B, or has a method using the class B." So if I want to strictly follow the dependency injection principle, the first one is the best option, isn't it? Given that I use $request->getController and $request->getAction inside the $dispatcher->dispatch() method. –  gaetanm Aug 24 at 12:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.