phppimple

Pass parameters to Pimple->container->factory


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.


Solution

  • 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);
    });