How can the logic of a Repository class in PHP be optimized to avoid overstepping its boundaries and potentially moving code to a different part of the application?

To optimize the logic of a Repository class in PHP and avoid overstepping its boundaries, it's essential to adhere to the Single Responsibility Principle and ensure that the Repository class is only responsible for data access operations. Any additional logic should be moved to a different part of the application, such as a Service class.

class UserRepository {
    private $db;

    public function __construct($db) {
        $this->db = $db;
    }

    public function getUserById($id) {
        // Database query to fetch user by id
    }
}

class UserService {
    private $userRepository;

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

    public function getUserById($id) {
        // Additional logic before calling UserRepository method
        return $this->userRepository->getUserById($id);
    }
}