dqf67993 2019-02-16 10:51
浏览 57

如何只提供在接口中声明的那些公共方法?

In Java, for example, this comes out of the box due to static nature of the language. But in PHP this could be also useful especially to keep a code secure and clean from an architectural point of view.

For example, we have the following code:

interface DocumentProcessorInterface

   public function process();

}

class GameSaveProcessorImpl implements DocumentProcessorInterface {

    public function process() {
        // do something useful
    }

    public function methodToSetSomethingFromFriendClass() {
       // setting private fields, some postponed initialization/resetting, etc
    }

}

Then, from some class (lets call it "friend class", because it lies side-by-side with the GameSaveProcessorImpl class and compelements it) we call method methodToSetSomethingFromFriendClass. Because of PHP duck typing such ability to call this method is also available to any alien client code, but this method is not for such usage. Alien (external) client code MUST use only DocumentProcessorInterface methods (this is one of the reasons why we use interfaces at all).

There are some solutions that come in mind.

1) Just leave it as is, but rename public methods that are not in interfaces, so it work as warning for those alien client code implementors, for example, rename methodToSetSomethingFromFriendClass to internalUseOnly_methodToSetSomethingFromFriendClass. Reduces risk of occassional usage, but doesn't prohibits calling methods technically.

2) Using adaptor (decorator) pattern. Pass to an external code only decorated instance which doesn't has methodToSetSomethingFromFriendClass method. It does solve problem of unwanted method access but complicates another parts of our code very much. It seems there is no overall profit.

3) Not really checked yet vialibity of this idea: utilize the following fact. Base class can declare protected method so all friend classes we control may be extended from that base class keeping our methodToSetSomethingFromFriendClass mehod marked as protected being effectively protected from external code, but callable from "friend" class. Technically this allows protection, but requires friend classes to inherit from common base class, drawbacks of such are well known.

Do you know anything better? Links to the articles are appreciated as well as sharing experience on this topic research.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 本题的答案是不是有问题
    • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
    • ¥15 C++使用Gunplot
    • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
    • ¥15 matlab数字图像处理频率域滤波
    • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
    • ¥15 ELGamal和paillier计算效率谁快?
    • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
    • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
    • ¥15 Arcgis相交分析无法绘制一个或多个图形