「Php/laravel/laravel5/DI」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→Method Injection) |
|||
行58: | 行58: | ||
{ | { | ||
echo $service->doSomething(); | echo $service->doSomething(); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | ==複数サービスコンテナを追加する場合のサンプル== | ||
+ | -App/Provider/AppServiceProvider.php | ||
+ | class AppServiceProvider extends ServiceProvider | ||
+ | { | ||
+ | public function register() | ||
+ | { | ||
+ | $this->app->bind('Service', function ($app) { | ||
+ | return new Service(); | ||
+ | }); | ||
+ | $this->app->bind('Client', function ($app) { | ||
+ | return new Client($app->make('Service')); | ||
+ | }); | ||
+ | } | ||
+ | } | ||
+ | -App/Controller/IocController.php | ||
+ | namespace App\Http\Controllers; | ||
+ | use Illuminate\Http\Request; | ||
+ | use App\Http\Requests; | ||
+ | use App\Http\Controllers\Controller; | ||
+ | use App\Services\Client; | ||
+ | class IocController extends Controller | ||
+ | { | ||
+ | public function index() | ||
+ | { | ||
+ | $client = app('Client'); | ||
+ | echo $client->doSomething(); | ||
} | } | ||
} | } |
2017年9月10日 (日) 01:47時点における版
目次
IoCとは
Inversion of Control(制御反転)
Laravelで使えるクラス間の依存を管理する管理ツールです。
PHPのDIについてはこちらを参考
php/pimple [ショートカット]]
Laravelには3種類方法がある
- App::make()
- Constructor Injection
- Method Injection (Laravel5から追加)
App::Make()
-app/Providers/AppServiceProvider.php
namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Services\Service; class AppServiceProvider extends ServiceProvider { public function register() { $this->app->bind('Service', function ($app) { return new Service(); }); } }
-App/Controller/IocController.php
use App\Http\Controllers\Controller; use App\Services\Service; class IocController extends Controller { public function index() { $service = app('Service'); echo $service->doSomething(); } }
Constructor Injection
Constructで記述すれば勝手にinstanceを生成してくれる
use App\Services\Service; class IocController extends Controller { public function __construct(Service $service) { echo $service->doSomething(); } }
Method Injection
Methodで記述すれば勝手にinstanceを生成してくれる
use App\Services\Service; class IocController extends Controller { public function index(Service $service) { echo $service->doSomething(); } }
複数サービスコンテナを追加する場合のサンプル
-App/Provider/AppServiceProvider.php
class AppServiceProvider extends ServiceProvider { public function register() { $this->app->bind('Service', function ($app) { return new Service(); }); $this->app->bind('Client', function ($app) { return new Client($app->make('Service')); }); } }
-App/Controller/IocController.php
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Services\Client; class IocController extends Controller { public function index() { $client = app('Client'); echo $client->doSomething(); } }