ThinkPhp는 본질적으로 Laravel과 같은 내장 의존성 주입 (DI) 컨테이너로 제작되지 않았지만 여러 접근 방식을 통해 DI를 구현할 수 있습니다. 가장 일반적이고 간단한 방법은 생성자 주입을 사용하는 것입니다. 이것은 종속성을 클래스의 생성자에게 인수로 전달하는 것을 의미합니다.
UserRepository
클래스에 의존하는 UserService
클래스가 있다고 가정 해 봅시다.
<code class="php">// UserRepository.php class UserRepository { public function getUserById($id) { // ... database logic to retrieve user ... return ['id' => $id, 'name' => 'John Doe']; } } // UserService.php class UserService { private $userRepository; public function __construct(UserRepository $userRepository) { $this->userRepository = $userRepository; } public function getUserProfile($id) { $user = $this->userRepository->getUserById($id); // ... additional logic to process user data ... return $user; } }</code>
컨트롤러 또는 응용 프로그램의 다른 부분에서 UserService
인스턴스화하고 UserRepository
인스턴스를 명시 적으로 전달합니다.
<code class="php">// UserController.php class UserController extends Controller { public function profile($id) { $userRepository = new UserRepository(); // Or retrieve from a service container if you're using one. $userService = new UserService($userRepository); $profile = $userService->getUserProfile($id); $this->assign('profile', $profile); $this->display(); } }</code>
이 수동 인스턴스화는 소규모 프로젝트에 적합합니다. 더 큰 응용 프로그램의 경우 서비스 컨테이너 (다음 섹션에서 논의)를 사용하는보다 강력한 접근 방식이 권장됩니다.
ThinkPhp에서 DI를 구현할 때 모범 사례에 따라 유지 가능성, 테스트 가능성 및 확장 성을 보장합니다. 주요 모범 사례에는 다음이 포함됩니다.
예, 타사 의존성 주입 컨테이너를 ThinkPhp와 통합 할 수 있습니다. 인기있는 선택에는 Pimple, Symfony의 종속성 주사 구성 요소 또는 Aura.di와 같은보다 완전한 용기가 있습니다.
통합은 일반적으로 다음과 같습니다.
여드름 (경량 컨테이너) 사용 예 :
<code class="php">// config/container.php $container = new Pimple\Container(); $container['userRepository'] = function ($c) { return new UserRepository(); }; $container['userService'] = function ($c) { return new UserService($c['userRepository']); }; // In your controller: $userService = $container['userService']; $profile = $userService->getUserProfile($id);</code>
이 예제는 Pimple과 함께 UserRepository
및 UserService
등록하는 방법을 보여준 다음 올바르게 주입 된 UserService
인스턴스를 자동으로 수신하는 UserRepository
인스턴스를 검색합니다.
ThinkPHP 프로젝트에서 DI를 구현하면 몇 가지 중요한 이점이 있습니다.
위 내용은 ThinkPhp 응용 프로그램에서 의존성 주입을 어떻게 구현합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!