Last active
July 7, 2016 13:56
-
-
Save deleugpn/ff86eb58f345664f51bfeed88f0e7c32 to your computer and use it in GitHub Desktop.
Dynamic Dependency Injection - MAKE SURE YOUR MODEL IMPLEMENTS ModelInterface!!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\ModelInterface; | |
use Illuminate\Http\Request; | |
use App\Http\Requests; | |
class CrudController extends Controller { | |
protected $model; | |
/** | |
* CrudController constructor. | |
* @param $model | |
*/ | |
public function __construct(ModelInterface $model) { | |
$this->model = $model; | |
} | |
/** | |
* Display a listing of the resource. | |
* | |
* @return \Illuminate\Http\Response | |
*/ | |
public function index() { | |
return $this->model->all(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
interface ModelInterface { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Route::get('/{model}', function($model){ | |
// Build App Object | |
$app = app(); | |
// Bind Dynamic DI | |
$app->bind(\App\ModelInterface::class, '\\App\\' . $model); | |
// Run controller and method | |
$controller = $app->make(\App\Http\Controllers\CrudController::class); | |
return $controller->callAction('index', []); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment