技術卡片 - 限制依賴注入的數量

心智極客發表於2019-12-23

通常,在類中注入的例項保持在 2-5 個,不宜過多。以下是反例

class UserController {

    protected $userService;
    protected $registerService;
    protected $userRepository;
    protected $strip;
    protected $mailer;
    protected $logger;

    public function __construct(
        UserService $userService,
        RegisterService $registerService,
        UserRepository $userRepository,
        Strip $strip,
        Mailer $mailer
    )
    {

    }
}

通過將其中一些類注入到子類可避免依賴注入的數量過多

class UserController {

    protected $userService;
    public function __construct(UserService $userService)
    {

    }
}

class UserService {

    protected $userRepository;
    protected $userEventRepository;

    public function __construct(UserRepository $userRepository, UserEventRepsotory $userEventRepository)
    {
        $this->userRepository = $userRepository;
        $this->userEventRepository = $userEventRepository;
    }
}

點選 連結,免費加入心智極客的知識星球分享群,共同成長。

相關文章