Load objects with parameters from Laravel IoC container

ぃ、小莉子 提交于 2019-12-06 14:53:38

I think you've dwelt to much on the IoC container there. Why not implement the Factory pattern and do a route binding instead of creating multiple controllers to handle different Imports? Crude example as follows:

  1. Create a route binder - edit your app/Provider/RouteServiceProvider.php's boot() method
public function boot(Router $router)
{
    parent::boot($router);

    // Add the statement below.
    $router->bind('import', 'App\RouteBindings@import');
}
  1. Create the App\RouteBindings class as app/RouteBindings.php
  2. Create an import() method with the following:
public function import($importKey, $route)
{
    switch ($importKey) {
        case 'import_abc':
            return new ImportAbc;
            break; // break; for good measure. ;)
        case 'import_xyz':
            return new ImportXyz;
            break;
        // and so on... you can add a `default` handler to throw an ImportNotFoundExeption.
    }
}
  1. Create a route for resolving an Import class.

Route::get('import/{import}/{method}', 'ImportController@handleImport');

Here, {import} will return the proper Import concrete class based on your URL.

  1. In your ImportController's handleImport() you can do the following:
public function handleImport(Import $import, $method)
{
    // $import is already a concrete class resolved in the route binding.
    $import->$method();
}

So when you hit: http://example.com/import/import_abc/seed, the route binding will return a concrete class of ImportAbc and store it in $import on your handleImport() method, then your handleImport() method will execute: $import->seed();. Tip: you should probably move other controller logic such as $import->status()->set() into the Import class. Keep your controllers thin.

Just make sure your Import classes have the same signature.

It's kinda like Laravel's Route Model Binding except you create the logic for the bindings.

Again, this is just a crude example but I hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!