在 PHP 的 Service 層實現解耦,通常采用以下幾種方法:
class UserService {
private $userRepository;
public function __construct(UserRepository $userRepository) {
$this->userRepository = $userRepository;
}
// ... 其他業務方法
}
interface UserServiceInterface {
public function createUser(array $userData);
// ... 其他業務方法
}
class UserServiceImpl implements UserServiceInterface {
private $userRepository;
public function __construct(UserRepository $userRepository) {
$this->userRepository = $userRepository;
}
public function createUser(array $userData) {
// ... 業務邏輯
}
// ... 其他業務方法
}
class ServiceLocator {
private $services = [];
public function set($name, $service) {
$this->services[$name] = $service;
}
public function get($name) {
if (!isset($this->services[$name])) {
throw new Exception("Service not found");
}
return $this->services[$name];
}
}
$serviceLocator = new ServiceLocator();
$serviceLocator->set('userService', new UserServiceImpl(new UserRepository()));
$userService = $serviceLocator->get('userService');
class UserServiceFactory {
public static function createUserService(UserRepository $userRepository) {
return new UserServiceImpl($userRepository);
}
}
$userRepository = new UserRepository();
$userService = UserServiceFactory::createUserService($userRepository);
通過以上方法,可以在 PHP 的 Service 層實現解耦,提高代碼的可維護性和可擴展性。