3

So I basically want to do this:

$this->container['Menu_builder'] = $this->container->factory(function ($c) {
    return new Menu_builder($parameter_1, $parameter_2);
});

Where $parameter_1 and $parameter_2 are passed in from the call, like this:

$menu_builder = $this->container['Menu_builder']('account', 'reset_password');

I know the above syntax is incorrect, but I want to pass these strings into the call to $this->container->factory.

Is this possible?

For example, if I wanted to instantiate the Menu_builder from various controller functions with different parameters for each controller function.

John Conde
  • 217,595
  • 99
  • 455
  • 496
Donal.Lynch.Msc
  • 3,365
  • 12
  • 48
  • 78

2 Answers2

3

FWIW, you can also include an anonymous function within your container.

$this->container['Menu_builder'] = function() {
    // do stuff here

    return function($parameter_1, $parameter_2) {
        return new Menu_builder($parameter_1, $parameter_2);
    };
};

Use this way:

$localfunc = $this->container['Menu_builder'];
$result = $localfunc($parameter_1, $parameter_2);

Notice that in this case I'm not using a factory. That's because you can execute the anonymous function with different values each time.

smcjones
  • 5,490
  • 1
  • 23
  • 39
2

You just can use use() to pass your variables to the anonymous functions, e.g.

//your parameters needs to be defined here:
$parameter_1 = "XY";
$parameter_2 = 42;

$this->container['Menu_builder'] = $this->container->factory(function ($c)use($parameter_1, $parameter_2) {
                                                                        //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ See here
    return new Menu_builder($parameter_1, $parameter_2);
});
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • And when defined in a service provider? I think parameters are meant to be passed by defining a container value - ie $container['param1'] = 'some value'. The anonymous function can then access via $container['param1'] – Brad Kent Sep 20 '15 at 02:21