世之奇伟、瑰怪、非常之观,常在于险远,而人之所罕至焉,故非有志者不能至也。
不是我自身的,却是我需要的,都是我所依赖的。一切需要外部提供的,都是需要进行依赖注入的。
依赖注入实现
女孩接口以及实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <?php
interface Girl {
}
class LoliGril implements Girl { public function __construct() { echo "LoliGril girl friend"; } public function make() { echo "love LoliGril "; } }
class Vixen implements Girl { public function __construct() { echo "Vixen girl friend"; } public function make() { echo "love Vixen "; } }
|
男孩需要一个女朋友
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Boy { protected $girl; public function __construct(Girl $girl) { $this->girl = $girl; }
public function yoyo() { $this->girl->make(); } }
$loliGirl = new LoliGril();
$boy = new Boy($loliGirl); $boy->yoyo();
?>
|
主动依赖和被动依赖
1 2 3 4 5 6 7 8 9 10 11
| function __construct() { $this->user=new UserModel(); }
function __construct(UserModel $user) { $this->user=$user; }
|
laravel依赖注入
新建一个类
app\Repositories\UserRepository.php
1 2 3 4 5 6 7 8 9
| <?php namespace App\Repositories;
class UserRepository { public function haha() { echo 'text'; } }
|
在HomeController中注入类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?php
namespace App\Http\Controllers; use App\Repositories\UserRepository;
class HomeController extends Controller { protected $userRepository; public function __construct(UserRepository $userRepository) { $this->userRepository = $userRepository; } public function index() { $this->userRepository->haha(); } }
|
以上代码可以直接运行
尝试注入接口,而不是类
新建一接口
app\Repositories\UserRepositoryInterFace.php
1 2 3 4 5 6 7 8
| <?php namespace App\Repositories;
interface UserRepositoryInterFace { public function haha(); public function hehe(); }
|
修改UserRepository.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?php namespace App\Repositories;
class UserRepository implements UserRepositoryInterFace { public function haha() { echo 'text'; } public function hehe() { } }
|
在HomeController中注入接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?php namespace App\Http\Controllers;
use App\Repositories\UserRepositoryInterFace;
class HomeController extends Controller { protected $userRepository; public function __construct(UserRepositoryInterFace $userRepositoryInterFace) { $this->userRepository = $userRepositoryInterFace; } public function index() { $this->userRepository->haha(); } }
|
绑定
我们依赖注入的是接口的时候, 需要做在AppServiceProvider(服务提供者)中做绑定,这样 laravel 就会帮你实例化依赖注入的类
app\Providers\AppServiceProvider.php
1 2 3 4 5 6 7
| use App\Repositories\UserRepository; use App\Repositories\UserRepositoryInterFace;
public function register() { $this->app->bind(UserRepositoryInterFace::class, UserRepository::class); }
|