linpf
V2EX  ›  PHP

为什么 PSR7 规范中, HTTP 响应必须要被视为无法修改的?

  •  
  •   linpf · Oct 19, 2017 · 4279 views
    This topic created in 3141 days ago, the information mentioned may be changed or developed.

    Responses are considered immutable; all methods that might change state MUST be implemented such that they retain the internal state of the current message and return an instance that contains the changed state.

    HTTP 响应是被视为无法修改的,所有能修改状态的方法,都必须有一套机制,在内部保持好原有的内容,然后把修改状态后的,新的 HTTP 响应实例返回。

    我的理解是,response 对象一旦生成就不允许修改,如果在控制器中需要添加一条新的 header 头信息,都需要克隆旧的 response 对象,然后在新对象中添加,返回新的对象。如果要添加 10 条 header 头信息,那么就要生成 11 个 response 对象。

    不知道我的理解是不是正确的,如果真的是这样,考虑不到它的意义,反而感觉是一种内存的浪费啊。为什么还要保留之前旧的 response 对象?直接在当前的 response 对象里添加就好了啊,反正也能返回一次。

    6 replies    2017-10-21 10:28:02 +08:00
    hantsy
        2
    hantsy  
       Oct 19, 2017
    React/Redux 引以自豪就是数据流的 immutable, 以大幅提高性能。但我不知道 PHP 底层实现与 React 是否有可比性。
    linpf
        3
    linpf  
    OP
       Oct 20, 2017
    @jessynt 18+1 的原因,上不了谷歌。

    @hantsy psr7 的 immutable 是用 PHP 实现的,不是在 C 底层实现的。只是为了满足 PSR 规范而已。性能上我看不到有啥优势。
    zjsxwc
        4
    zjsxwc  
       Oct 20, 2017
    感觉和 erlang 之类的消息不可变原则一样的原因
    zjsxwc
        5
    zjsxwc  
       Oct 20, 2017
    只能克隆创建新的, 不能修改原来的, 可以避免很多情况下的副作用
    linpf
        6
    linpf  
    OP
       Oct 21, 2017
    @zjsxwc 但是想了好久也想不出来会有什么副作用。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3185 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 12:35 · PVG 20:35 · LAX 05:35 · JFK 08:35
    ♥ Do have faith in what you're doing.