使用标记接口进行安全编程与里氏替换原则

问题描述 投票:0回答:1

我了解 LSP 以及为什么下面的代码给出:

PHP 致命错误:声明 UnauthenticatedUser::executeCommand(UnauthenticatedCommand $c) 必须是 与 /tmp/test.php 中的 User::executeCommand(Command $c) 兼容 13号线

但是,我认为这两个接口

Command
UnauthenticatedCommand
是等效的(因为它们只是标记接口)。

鉴于这些事实,什么是干净的[1]方法,使未经身份验证的用户无法执行除

UnauthenticatedCommand
之外的任何其他操作?

<?php

interface Command {
}

interface UnauthenticatedCommand extends Command {
}

interface User {
    public function executeCommand(Command $c);
}

class UnauthenticatedUser implements User {
    public function executeCommand(UnauthenticatedCommand $c) {
    }
}

[1] 干净意味着不使用内省,既不以编程方式也不使用引擎的支持 (

instanceof
)。

php oop
1个回答
0
投票

你可以这样做:

interface Command {
}

interface UnauthenticatedCommand extends Command {
}

interface User {
   // some general methods
}

interface AuthenticatedUser implements User {
   public function executeCommand(Command $c);
}

interface UnauthenticatedUser implements User {
   public function executeCommand(UnauthenticatedCommand $c);
}
© www.soinside.com 2019 - 2024. All rights reserved.