2

I would like to find a good way to pass a pre-configured object to a controller. I know that I can use the IoC like below:

Mycontroller extends extends \Illuminate\Routing\Controllers\Controller {

    //i can only use one config uless i pass Request data
    $this->config = App::make('MyconfigObject');

}

but this seems to have the limitation of only being able to use one config. I would rather do something like the following:

Route::get('some-route', function()
{
    $config = Config::get('some.config');
    $object = new MyConfigObject($config);
    Route::dispatch(MyController($object));
});

The reason I would like to do this is that I would like to dispatch the same controller, but with different configuration for several routes.

1 Answer 1

1

I'm not totally satisfied with this method but its the best I've come up with so far, using the IoC's automatic resolution.

bootstrap/stat.php

/*
* bindings to the IoC container
*/
$app->singleton('MyNamespace\Transfer\TransferStategyInterface', function() {
    $config = Config::get('transfer-strategy');
    return new LocalTransferStrategy($config);
});


use MyNamespace\Transfer\TransferStategyInterface;

TransferController.php

use MyNamespace\Transfer\TransferStategyInterface;


class TransferController extends BaseController {

    protected $transferStrategy;

    public function __construct(TransferStategyInterface $transferStrategy = null)
    {
        $this->transferStrategy = $transferStrategy;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I used to use your approach before. Now I use App::make() to instantiate objects directly in the method. This way you don't need to create objects that won't be needed in certain methods and keeps your Controller simple. Other tip: I don't use backslaskes in my app bindings. I let that to the automatic resolution. I use dots like App::make('my.special.method', array($arg1, $arg2)). This way I can have several constructors of the same class with a descriptive instantiation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.