views:

100

answers:

2

Example:

Class A {
     public function __construct() {
         $this->b_Instance = new B();
     }
     public caller() {
         $this->b_Instance->call_me($param1,$param2,$param3);
     }
}

Class B {
     public function __construct() {
         //lots of variables here
     }

     public function call_me($param1,$param2,$param3) {
         ...
         //do something with param1, but nothing with param2 and 3. just pass it.
         $this->do_something($param2,$param3);
     }

     private function do_something($param2,$param3) {
         ...
         //do something with param2 and 3
     }

     //lots of other functions here
}

Normally I'd add it to the constructor of B as a class variable, however the constructor is already populated with lots of variables, and the parameters passed by A->caller() is only used by B->call_me and B->do_something anyway.

What is the elegant way of preventing this extra-passing of parameters from B->call_me to B->do_something? Or is this even a problem and I just have OCD?

Additional: Notice that B->call_me does nothing with param2 and 3, but only passes it to B->do_something which is a private function.

A: 

If those variables are parameters related only to call_me and do_something, they should be passed as parameters ^^

What I mean is :

  • they don't have to be stored as class-variables
  • they will obvisouly not be global / session / anyhing like that.


A solution might be to regroup those parameters in an associative array, and pass only one array as parameter (which means not having to change the methods defininitions each time you want to add a parameter)... But I don't like this idea : your phpdoc will not be as good as before, you will not have hinting in your IDE, ...


Maybe one question would be : are your methods not doing "too many things" ?

ie, a method should do one small task ; maybe your are doing lots of tasks ? In this case, maybe splitting them into several smaller methods could help ?

Pascal MARTIN
They are split up, with each method doing one thing only. U updated my question by the way, to make it more clear
mives
I meant "I" updated my question.
mives
I decided that the method does do a lot of things. Refactored.
mives
A: 

Other solution would be to use an object to encapsulate those params (maybe they are related and would benefit from combining then into an object), so you would have:

$this->call_me(new SomeObject($param1,$param2,$param3));

But to be honest, if passing those params is a problem in your case I would rehink the design, if your class has to many params in constructor that in most cases means that it has to big responsibility and should be refactored in smaller clases.

krzyk
Hi, it's not really an issue to me (not placing call_me's params on the constructor) since I don't plan to place it there anyway since it's only used by two functions.
mives