在 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 层实现解耦,提高代码的可维护性和可扩展性。