# RFC: Server-Side Request and Response Objects (v2)

- Thread: https://externals.io/message/108436
- Original archive: https://news-web.php.net/php.internals/108436
- Started by Paul M. Jones on 2020-02-10T16:18:51+00:00
- Messages: 103
- RFC: Server-Side Request and Response Objects (Declined) — https://externals.io/rfc/request_response.md
- Page 1 of 5: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/108436.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #108436 — Paul M. Jones — 2020-02-10T16:18:51+00:00

URL: https://externals.io/message/108436#108436

Hi Internals,

After a couple of years of incubation, I am happy to offer a second version of this RFC:

  https://wiki.php.net/rfc/request_response

It proposes an object-oriented approach around request and response functionality already existing in PHP, in order to reduce the global-state problems that come with superglobals and the various response-related functions.

The SQLite "about" page says, "Think of SQLite not as a replacement for Oracle but as a replacement for `fopen()`." <https://www.sqlite.org/about.html>  Likewise, think of this RFC not as a replacement for HttpFoundation or PSR-7, or as a model of HTTP messages, but as an object-oriented alternative to superglobals, `header()`, `setcookie()`, `setrawcookie()`, and so on.

Thanks in advance for your time and consideration while evaluating it.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #108437 — michal.brzuchalski@gmail.com — 2020-02-10T16:46:43+00:00

URL: https://externals.io/message/108436#108437 · In reply to: #108436

Hi Paul,

thanks for bringing it back. Got some questions:

1. In your RFC $_ENV is bound to $request.

Looking at HttpFoundation can see it's build from $_GET, $_POST, $_FILES,
$_COOKIE, $_SESSION
and then looking at PSR ServerSideRequest it's build from $_COOKIE, $_GET,
$_POST, $_FILES, $_SERVER
but none of them bounds $_ENV.

Server environment variables basically don't change over time when server
process runs.
What is the specific use case that requires them to be coupled with
$request instance?

2. In your RFC all headers are mapped to $request properties

This behaviour is unclear and unusual to me, for eg. in summary can see
that if
server request has "Header-Name" it is found in
$_SERVER["HTTP_HEADER_NAME"] and
that one is bound to $request->headers["header-name"], ok but the next line
with example for
"Content-Type" shows that it's bound to $request->contentType - which means
probably that it can
be accessed in $request->headers["content-type"] as well, right? seems
logic.

Going further, for eg. $_SERVER["PHP_AUTH_PW"] is bound to $request->authPw
and then
what will happen if the request will receive "Auth-Pw" header?

a) It'll be bound to $request->headers["auth-pw"] ?

b) It'll be bound to $request->authPw ?

c) None of above.

With those above I would see a set of getters like getContentType() or
getAuthPassword() etc.
instead of ServerRequest instance properties and a single point to retrieve
header values just like
well known ParameterBag's from HttpFoundation to operate on get, post,
headers etc.

BR,
--
Michał Brzuchalski

---

## #108438 — Mark Randall — 2020-02-10T17:02:02+00:00

URL: https://externals.io/message/108436#108438 · In reply to: #108436

> Hi Internals,
> Thanks in advance for your time and consideration while evaluating it.

I suspect this is a similar sentinment to the previous version, but I 
can personally see no major benefit to having this as a core extension.

I think the reality is that discussing it "on its own merits" is to 
completely ignore the wider ecosystem that already performs these 
functions, with more capabilities, and with potentially hundreds of 
thousands of implementations already in place.

Does it add capabilities which cannot exist in userland or cannot exist 
in a reasonably performant way? Doesn't seem so except for a readonly 
property.

If not, leave it to userland.

Mark Randall

---

## #108439 — Mike Schinkel — 2020-02-10T17:32:42+00:00

URL: https://externals.io/message/108436#108439 · In reply to: #108436

> 
> 
> Hi Internals,
> 
> After a couple of years of incubation, I am happy to offer a second version of this RFC:
> 
>  https://wiki.php.net/rfc/request_response
> 
> It proposes an object-oriented approach around request and response functionality already existing in PHP, in order to reduce the global-state problems that come with superglobals and the various response-related functions.
> 
> The SQLite "about" page says, "Think of SQLite not as a replacement for Oracle but as a replacement for `fopen()`." <https://www.sqlite.org/about.html>  Likewise, think of this RFC not as a replacement for HttpFoundation or PSR-7, or as a model of HTTP messages, but as an object-oriented alternative to superglobals, `header()`, `setcookie()`, `setrawcookie()`, and so on.
> 
> Thanks in advance for your time and consideration while evaluating it.

I like this, a lot. 

Having a language _standard_ approach means that I could depend on it existing and that all (new) userland code I might want to incorporate into a project would be compatible rather than the current state of 100! different incompatible implementations across frameworks.  

I had numerous questions and concerns, but after reading through the RFC and the associated links I think you addressed most of them.

I do have questions about ServerResponse.  It is not clear how that interacts with existing echo, `header()`, `setcookie()`, etc?  You say it creates a buffer; is $responseSender->send($response) effectively the same as having issued regular echo, `header()`, `setcookie()`, etc. all at once?  And that there is no global buffer but instead the application would have to manage using a shared $response on its own because each instance of $response has it's own buffer and can be sent at any time into the existing output "stream?"

Regarding ServerRequest I saw the comment about using a factory instead of creating an instance and your reason for not going that route. How about instead creating an empty mutable object with the constructor and then a method with an optional array parameter that adds the values and "locks" it to be mutable, i.e.

$request = new ServerRequest();
$request->initialize();
// OR
$request->initialize([
    '_SERVER' => [
        'foo' => 'bar',
    ],
]);

With this approach someone could create a class that contains the ServerRequest and build the object up to be anything they like which could be useful for testing, i.e.

$request = new ServerRequest();
$request->get = [ 'foo' => 'bar' ];
$request->cookie = [ 'id' => 123 ];
$request->nv = $_ENV;
$request->server = $_SERVER;
$request->lock();

I would also suggest considering to add get(), post(), `request()`, `cookie()`, server() and `end()` methods to ServerRequest that would incorporate the functionality of `filter_input()`.  Otherwise we have to bypass the objects to get filtering.

In general I think this would definitely be a nice enhancement to PHP, IMO.  It would be great to be able to deprecate use of $GLOBALS, etc. with a language _standard_ approach, and flag their use as problematic in any of our code. 

Would you not also add an option to generate a warning when using them for those who want to deprecate their use in their own code (deprecating across the board would be too extreme give how much CMS and framework code uses them intimately.)

Thanks in advance for considering.

-Mike

---

## #108440 — johannes@schlueters.de — 2020-02-10T20:44:29+00:00

URL: https://externals.io/message/108436#108440 · In reply to: #108436

Hi,


> After a couple of years of incubation, I am happy to offer a second
> version of this RFC:
> 
>   https://wiki.php.net/rfc/request_response

What indication is there that this will be more successfull than the
filter API? The filter API was our previous attempt to improve upon
input handling. With this new API we have three major ways
(superglobals, filter, new API) 

Historically PHP isn't really successful in providing higher level APIs
to things and I think leaving this to userland is very viable, since
composer and performance improvements in later PHP 5 and PHP 7.

Also use of $_* is fast to grep for and gives me directly in the grep
an idea about the mess-factor of a code base, tracing all calls to a
member of an instance of a class is harder. (and yes, references etc.
to super globals aren't trivial to trace, but also rare)

Let PHP provide the access to the data and promote the API library of
the year.

johannes

---

## #108453 — Jan Schneider — 2020-02-11T09:33:57+00:00

URL: https://externals.io/message/108436#108453 · In reply to: #108436

Zitat von Paul M. Jones <pmjones@pmjones.io>:

> Hi Internals,
>
> After a couple of years of incubation, I am happy to offer a second  
> version of this RFC:
>
>   https://wiki.php.net/rfc/request_response
>
> It proposes an object-oriented approach around request and response  
> functionality already existing in PHP, in order to reduce the  
> global-state problems that come with superglobals and the various  
> response-related functions.

I like this proposal a lot, since it provides a clear, concise  
interface to these commonly uses, yet inconveniant to use, existing  
functions and variables without having to always use a full-featured  
userland library.
Speaking of interfaces: since you suggest using decoration and  
composition over extension for ServerResponse, I am missing a  
ServerResponseInterface, so that you can easily typehint such userland  
decorators.

-- 
Jan Schneider
The Horde Project
https://www.horde.org/

---

## #108471 — Albert Casademont — 2020-02-11T12:42:10+00:00

URL: https://externals.io/message/108436#108471 · In reply to: #108453

This is very interesting, thanks!

Would it make sense to also add an INI setting to disable superglobals and
response functions?




>
> Zitat von Paul M. Jones <pmjones@pmjones.io>:
>
> > […]
>
> I like this proposal a lot, since it provides a clear, concise
> interface to these commonly uses, yet inconveniant to use, existing
> functions and variables without having to always use a full-featured
> userland library.
> Speaking of interfaces: since you suggest using decoration and
> composition over extension for ServerResponse, I am missing a
> ServerResponseInterface, so that you can easily typehint such userland
> decorators.
>
> --
> Jan Schneider
> The Horde Project
> https://www.horde.org/

---

## #108476 — Reindl Harald privat — 2020-02-11T12:59:24+00:00

URL: https://externals.io/message/108436#108476 · In reply to: #108471

Am 11.02.20 um 13:42 schrieb Albert Casademont:
> This is very interesting, thanks!
> 
> Would it make sense to also add an INI setting to disable superglobals and
> response functions?

no because changing basic language behavior that way is not helpful for
code meant to run everywhere and not stop working just because tomorrow
someone changed a random ini setting

---

## #108479 — Paul M. Jones — 2020-02-11T13:14:35+00:00

URL: https://externals.io/message/108436#108479 · In reply to: #108437

Hi Michał,

Good to hear from you!

(While writing this, I realized I made a couple of mistakes in the RFC examples related to CONTENT_LENGTH and CONTENT_TYPE that might have caused confusion; I have now fixed them.)


> 
> 
> Hi Paul,
> 
> thanks for bringing it back. Got some questions:
> 
> 1. In your RFC $_ENV is bound to $request.
> 
> Looking at HttpFoundation can see it's build from $_GET, $_POST, $_FILES, $_COOKIE, $_SESSION and then looking at PSR ServerSideRequest it's build from $_COOKIE, $_GET, $_POST, $_FILES, $_SERVER but none of them bounds $_ENV.
> 
> Server environment variables basically don't change over time when server process runs. What is the specific use case that requires them to be coupled with $request instance?

I have no specific use case; I recall that $_ENV showed up in more than a couple of reviewed implementations, and so included it here. If there is no objection from John Boehr (who did the majority of heavy lifting C), or from anyone else, then I would be fine with removing the ENV-related element. I have no strong feelings on $_ENV representation either way.


> 2. In your RFC all headers are mapped to $request properties
> 
> This behaviour is unclear and unusual to me, for eg. in summary can see that if server request has "Header-Name" it is found in $_SERVER["HTTP_HEADER_NAME"] and that one is bound to $request->headers["header-name"], ok but the next line with example for "Content-Type" shows that it's bound to $request->contentType - which means
> probably that it can be accessed in $request->headers["content-type"] as well, right? seems logic.

I'm not sure if that is a question/comment/criticism, or a statement of "OK so far, but ...". Please bear with me, so I can make sure I'm addressing your question properly.

First: Not *all* headers are mapped to $request properties; the only ones that get special $request properties are the ones that showed up as frequently getting special treatment in other implementations.

Next: the $header array is populated by all $_SERVER['HTTP_*'] values, plus $_SERVER['CONTENT_TYPE'] and $_SERVER['CONTENT_LENGTH']. The latter two do not follow the 'HTTP_*' pattern because of RFC 3875; they come in as (e.g.) `Content-Type: text/plain`, so you might expect $_SERVER['HTTP_CONTENT_TYPE'], but RFC 3875 dictates otherwise.

Finally: yes, $request->header['content-type'] is available at the same time as $request->contentType, but they are not quite the same thing. The Content-Type header also allows you to specify a charset, which value gets populated into $request->contentCharset. So, you can read these values these ways:

- $request->header['content-type'] => 'text/plain; charset=UTF-8' (the original header)
- $request->contentType => 'text/plain' (parsed out by ServerRequest)
- $request->contentCharset => 'UTF-8' (parsed out by ServerRequest)

Likewise, PHP puts `Content-Length: 123' into $_SERVER['CONTENT_LENGTH']; ServerRequest additionally puts it into $request->headers['content-length'] as a string; and then further tries to represent the value as an integer in $request->contentLength. So:

- $request->server['CONTENT_LENGTH'] => (string) '123'
- $request->headers['content-length'] => (string) '123'
- $request->contentLength => (int) 123

My apologies if all of that was stuff you already knew and understood. (And if you did not already know it, maybe that means I should write up a narrative of the logic being applied.)


> Going further, for eg. $_SERVER["PHP_AUTH_PW"] is bound to $request->authPw and then what will happen if the request will receive "Auth-Pw" header?

In that example, PHP would populate two $_SERVER elements: 'PHP_AUTH_PW' from the password, and 'HTTP_AUTH_PW' from the header. ServerRequest only populates PHP_AUTH_PW into $authPw; the HTTP_AUTH_PW value would (per the above description) go into $request->headers['auth-pw'].

I hope that made sense; let me know if it did not.


> With those above I would see a set of getters like getContentType() or getAuthPassword() etc. instead of ServerRequest instance properties and a single point to retrieve header values just like well known ParameterBag's from HttpFoundation to operate on get, post, headers etc.

Does the above explanation help to modify your preferences here? If not, we can continue talking about it.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #108489 — Ben Ramsey — 2020-02-11T16:58:40+00:00

URL: https://externals.io/message/108436#108489 · In reply to: #108436

> 
> 
> Hi Internals,
> 
> After a couple of years of incubation, I am happy to offer a second version of this RFC:
> 
>  https://wiki.php.net/rfc/request_response
> 
> It proposes an object-oriented approach around request and response functionality already existing in PHP, in order to reduce the global-state problems that come with superglobals and the various response-related functions.
> 
> The SQLite "about" page says, "Think of SQLite not as a replacement for Oracle but as a replacement for `fopen()`." <https://www.sqlite.org/about.html>  Likewise, think of this RFC not as a replacement for HttpFoundation or PSR-7, or as a model of HTTP messages, but as an object-oriented alternative to superglobals, `header()`, `setcookie()`, `setrawcookie()`, and so on.
> 
> Thanks in advance for your time and consideration while evaluating it.



Regarding the array of arrays for $accept* and $forwarded, what are your thoughts on using value objects with properties, rather than arrays with keys?


AcceptValue

* string $value
* string $quality
* array $params
* ?string $type
* ?string $subtype


ForwardedValue

* string $by
* string $for
* string $host
* string $proto


Cheers,
Ben

---

## #108491 — Albert Casademont — 2020-02-11T17:22:54+00:00

URL: https://externals.io/message/108436#108491 · In reply to: #108476

On Tue, Feb 11, 2020 at 1:59 PM Reindl Harald (privat) <harry@rhsoft.net>
wrote:

>
>
> Am 11.02.20 um 13:42 schrieb Albert Casademont:
> > […]
> and
> > […]
>
> no because changing basic language behavior that way is not helpful for
> code meant to run everywhere and not stop working just because tomorrow
> someone changed a random ini setting
>

That could be said for all INI settings: yes they can break things if you
touch them without knowing what they do.

I think it might make sense to be able to disable superglobals and response
functions if your codebase is committed to using the new classes, much like
the old "register_globals" did. Why pollute the global namespace if you
don't need them?

---

## #108493 — Paul M.Jones — 2020-02-11T18:30:25+00:00

URL: https://externals.io/message/108436#108493 · In reply to: #108436

Hi Mark,

> 
> 
> I suspect this is a similar sentinment to the previous version, but I can personally see no major benefit to having this as a core extension.
> 
> I think the reality is that discussing it "on its own merits" is to completely ignore the wider ecosystem that already performs these functions, with more capabilities, and with potentially hundreds of thousands of implementations already in place.
> 
> Does it add capabilities which cannot exist in userland or cannot exist in a reasonably performant way? Doesn't seem so except for a readonly property.
> 
> If not, leave it to userland.

I completely understand that sentiment; I recognize that it is shared by others on this list and elsewhere. But if you'll allow me, I'd like to present a counterargument in relation to previous PHP extensions.

When ext/pdo was added to core, there was already a "wider ecosystem that already performs these functions, with more capabilities, and with potentially hundreds of thousands of implementations already in place." Some of those implementations at the time included (I'm working from memory here) AdoDB, Metabase, MDB, PEAR_DB, and many more that I cannot recall.

PDO did not (to my knowledge) "add capabilities which cannot exist in userland or cannot exist in a reasonably performant way". (I'll grant that FETCH_INTO_OBJECT setting properties directly without using the constructor was not possible in userland, but that's an exception that tests the rule.) Indeed, PDO had a relatively reduced feature set in comparison to some of those userland libraries, especially AdoDB.

And yet, PDO has turned out to be of great benefit, because it brought together features into core that (figuratively speaking) everybody needed and was rewriting in userland over and over.

PDO is the strongest example here, but depending on how you count, there are 2-3 other extensions that also serve: ext/date, ext/phar, and (reaching back to antiquity) ext/session.

So, there is a long history of widely-needed userland functionality being brought into core. I would say this RFC is a pretty tame example of doing so; the proposal presented here is very similar to the way PHP itself already does things, just wrapped in object properties and methods, and is very similar to how things are being done across a wide swath of userland.

Now, it is possible that the objections you raise *should* have prevented PDO (et al.) from going into core. If that is the case, and (in hindsight) we think it was a mistake to allow them, then consistency alone makes your objections valid here as well.

However, if (in hindsight) it was *not* a mistake to allow those extensions, then the raised objections are not especially strong arguments against this RFC. That's not to say "because PDO was allowed into core, this RFC must therefore be allowed into core" but to say "those objections alone were not a barrier to PDO, so they alone should not be a barrier to this RFC".

I hope that's an understandable counterargument, even if you don't agree with it.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #108507 — Paul M. Jones — 2020-02-12T12:47:31+00:00

URL: https://externals.io/message/108436#108507 · In reply to: #108439

Hi Mike,


> I like this, a lot. ... In general I think this would definitely be a nice enhancement to PHP, IMO.

Thanks for saying!


> I do have questions about ServerResponse.  It is not clear how that interacts with existing echo, `header()`, `setcookie()`, etc?  You say it creates a buffer; is $responseSender->send($response) effectively the same as having issued regular echo, `header()`, `setcookie()`, etc. all at once?

That's correct. ServerResponse stores the (mutable) state of the response; ServerResponseSender reads from the ServerResponse and calls `header()`, `setcookie()`, etc. with its values.


> each instance of $response has it's own buffer and can be sent at any time

That is also correct.


> Regarding ServerRequest ... How about instead creating an empty mutable object with the constructor and then a method with an optional array parameter that adds the values and "locks" it to be mutable, i.e.
> 
> $request = new ServerRequest();
> $request->initialize();
> // OR
> $request->initialize([
>    '_SERVER' => [
>        'foo' => 'bar',
>    ],
> ]);
> 
> With this approach someone could create a class that contains the ServerRequest and build the object up to be anything they like which could be useful for testing, i.e.
> 
> $request = new ServerRequest();
> $request->get = [ 'foo' => 'bar' ];
> $request->cookie = [ 'id' => 123 ];
> $request->nv = $_ENV;
> $request->server = $_SERVER;
> $request->lock();

That is essentially what it does now; the difference is that you mimic the $GLOBALS array at construction time, and the instance locks automatically:

    $request = new ServerRequest([
        '_GET' => ['foo' => 'bar'],
        '_COOKIE' => ['id' => 123],
        '_SERVER' => $_SERVER,
    ]);
    // $request is now locked

The class that contains ServerRequest would then build up that array for the constructor.

Do you feel that's close enough to what you're asking for?


> I would also suggest considering to add get(), post(), `request()`, `cookie()`, server() and `end()` methods to ServerRequest

First, I'd have to decline adding `request()` (or $request) at all; my opinion is that one ought to be reading from $get, $post, $cookies, etc. specifically, not from a pool of those values.

Second, if I understand you correctly, I much prefer the property access over the method getter; it just "looks and feels better":

    $request->get['foo']
    vs
    $request->get()['foo'];

Let me know if that makes sense to you or not.


> incorporate the functionality of `filter_input()`.  Otherwise we have to bypass the objects to get filtering.

I don't think you'd have to bypass the objects to get filtering; unless I am missing something, this ...

    $foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_SPECIAL_CHARS);

... would easily become this:

    $foo = filter_var($request->get['foo'], FILTER_SANITIZE_SPECIAL_CHARS);

There might be behavioral nuances between the two, but the point is that you can still do filtering.


> Would you not also add an option to generate a warning when using them for those who want to deprecate their use in their own code (deprecating across the board would be too extreme give how much CMS and framework code uses them intimately.)

That seems a bit much at this point. ;-)

I hope that answers all your questions.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #108510 — Paul M. Jones — 2020-02-12T16:54:11+00:00

URL: https://externals.io/message/108436#108510 · In reply to: #108440

Hi Johannes,


> What indication is there that this will be more successfull than the
> filter API?

Fair question. While I can't say how successful (or not) ext/filter has been, I *can* say that the proposal does not present extraordinary or dramatically different ways of working than PHP does currently.

The extent of the RFC is only to provide behaviors similar to what PHP already does, in object-oriented dress. That is, whereas ext/filter might have been been described as "a new and different way of working", the concepts and functions in this RFC (even down to the method and property names!) should be immediately familiar even to junior PHP developers.


> Historically PHP isn't really successful in providing higher level APIs
> to things and I think leaving this to userland is very viable, since
> composer and performance improvements in later PHP 5 and PHP 7.

I addressed the "userland" argument in my response to Mark Randall; please forgive me for not repeating it here.


> Also use of $_* is fast to grep for and gives me directly in the grep
> an idea about the mess-factor of a code base, tracing all calls to a
> member of an instance of a class is harder. (and yes, references etc.
> to super globals aren't trivial to trace, but also rare)

I feel your pain! I do a lot of legacy work too. The `$_` signature makes grepping easy, so that I can find places where there is spooky-action-at-a-distace from globally mutable state.

However, ServerRequest is intended to reduce or remove that globally mutable state. The $request->get property is readonly, and neither global nor superglobal. So, while it is tougher to grep for `->get` and know that you have found a ServerRequest property, the *need* to do so should be much less even in legacy codebases.


> Let PHP provide the access to the data and promote the API library of the year.

"API library of the year" -- heh.

To be fair, though, the API presented by ServerRequest and ServerResponse is highly similar to that presented by PHP itself; far from being "API of the year" it honors existing PHP functionality quite closely.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #108512 — Niklas Keller — 2020-02-12T18:20:56+00:00

URL: https://externals.io/message/108436#108512 · In reply to: #108436

> Hi Internals,
>
> After a couple of years of incubation, I am happy to offer a second version of this RFC:
>
>   https://wiki.php.net/rfc/request_response
>
> It proposes an object-oriented approach around request and response functionality already existing in PHP, in order to reduce the global-state problems that come with superglobals and the various response-related functions.
>
> The SQLite "about" page says, "Think of SQLite not as a replacement for Oracle but as a replacement for `fopen()`." <https://www.sqlite.org/about.html>  Likewise, think of this RFC not as a replacement for HttpFoundation or PSR-7, or as a model of HTTP messages, but as an object-oriented alternative to superglobals, `header()`, `setcookie()`, `setrawcookie()`, and so on.
>
> Thanks in advance for your time and consideration while evaluating it.

Hey Paul,

I think the request / response API is entirely fine being solved in
userland instead of in php-src. However, since you already made such a
proposal, I want to give some feedback:

Naming

I think we shouldn't take over the naming of the super globals, e.g.
$_GET really contains the query parameters and has nothing to do with
GET or POST, so $request->getQueryParameter(...) would be a better
name.

Type Safety

I think the API should be type safe. Currently $request->get['key']
can be null | string | string[] | ... Most parameters only appear a
single time, so a method returning the first parameter value or null
could be used instead.

API Issues

I don't see any reason to keep specials such as
$_SERVER['HTTP_X_REQUESTED_WITH'] vs. $request->requestedWith, which
is just another HTTP header.

If there's $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] => $request->method
and $_SERVER['REQUEST_METHOD'] => $request->method, how can I get the
original  (actual) method?

Given 'echo $content; => $response->setContent($content);', shouldn't
this rather be something like `addContent()`? How does streaming
responses work? There's ServerResponseSender, but I think this should
be part of the Response API.

The Request object should be mutable, e.g. you might want to change
the client IP to be based on a x-forwarded-header instead of the TCP
source address.

Other Commentary

> A: It supports async exactly as much as PHP itself does.

Not really. PHP has built-in stream_select / non-blocking streams, so
supports the tools required for async out of the box.

Regards, Niklas

---

## #108511 — Mike Schinkel — 2020-02-12T18:21:58+00:00

URL: https://externals.io/message/108436#108511 · In reply to: #108507

> 
> 
> That is essentially what it does now; the difference is that you mimic the $GLOBALS array at construction time, and the instance locks automatically:
> 
>    $request = new ServerRequest([
>        '_GET' => ['foo' => 'bar'],
>        '_COOKIE' => ['id' => 123],
>        '_SERVER' => $_SERVER,
>    ]);
>    // $request is now locked
> 
> The class that contains ServerRequest would then build up that array for the constructor.
> 
> Do you feel that's close enough to what you're asking for?

No.  IMO it should not lock until explicitly locked.  

Why?  Take a look at WordPress.  It does a lot of "fixup" to $_SERVER` variables — to deal with badly implemented web servers — to ensure all known variables have a value and that the format of the value is consistent.  

If you always lock on instantiation then WordPress would have to default to continue using $_SERVER.  Or subclass it, but that would generate copying overhead and it would be too easy for programmers to just call ServerRequest() again.

Another option actually would be to allow changes to $_SERVER prior to instantiating ServerRequest() the first time.

Frankly though, none of those options should ideal, include your current proposed solution.  Basically making a copy of $_SERVER so ServerRequest() is not authoritative, but alternately your solution does not allow frameworks to fix the inconsistency across servers.

Maybe what would be needed is a single ServerRequest::initialize( $closure ) where the ciosure can do the fixup. This would need to be called before new ServerRequest() is called after which ServerRequest would be locked for changes.

> First, I'd have to decline adding `request()` (or $request) at all; my opinion is that one ought to be reading from $get, $post, $cookies, etc. specifically, not from a pool of those values.

That's definitely fair.  I almost did not include `request()` in my suggestion but did because PHP has $_REQUEST.

> Second, if I understand you correctly, I much prefer the property access over the method getter; it just "looks and feels better":
> 
>    $request->get['foo']
>    vs
>    $request->get()['foo'];
> 
> Let me know if that makes sense to you or not.

I was actually proposing a third option:

$request->get('foo');

Or as I like to do in my own code (to indicate where it comes from):

	$request->GET('foo');

Why a method is important is to support filters (I guess I assumed that was obvious but realize now it was not.) For example:

	$request->get('redirect', FILTER_SANITIZE_URL);
	$request->get('product_id', FILTER_SANITIZE_NUMBER_INT);
	$request->get('email', FILTER_SANITIZE_EMAIL);

You could potentially even have scoped, easier to remember constants that can work with autocomplete:

	$request->get('redirect', ServerRequest::URL);
	$request->get('product_id', ServerRequest::INT);
	$request->get('email', ServerRequest::EMAIL);


> incorporate the functionality of `filter_input()`.  Otherwise we have to bypass the objects to get filtering.
> 
> I don't think you'd have to bypass the objects to get filtering; unless I am missing something, this ...
> 
>    $foo = filter_input(INPUT_GET, 'foo', FILTER_SANITIZE_SPECIAL_CHARS);
> 
> ... would easily become this:
> 
>    $foo = filter_var($request->get['foo'], FILTER_SANITIZE_SPECIAL_CHARS);
> 
> There might be behavioral nuances between the two, but the point is that you can still do filtering.


But wouldn't it be 1000% easier to write and easier to read code like this?

$foo = $request->get( 'foo', ServerRequest::SPECIAL_CHARS);


Since filtering $_GET elements is 100% done when accessing them it makes sense to streamline the operation.  But if a developer does not want to filter, they just do this:

$foo = $request->get( 'foo' );


> > […]
> 
> That seems a bit much at this point. ;-)

Really?  Seems like this and some guard code is all it would take:

ini_set( "disallow_superglobals", true);

-Mike

---

## #108513 — Mike Schinkel — 2020-02-12T18:39:27+00:00

URL: https://externals.io/message/108436#108513 · In reply to: #108512

> 
> I think the request / response API is entirely fine being solved in
> userland instead of in php-src.

I want to disagree in support of this RFC. 

While is *has* been solved in userland, but it has been solved 25+ times in 25+ different incompatible ways.  This RFC would allow for a *single* solution that is compatible across all frameworks, and frameworks could create a shim to support their existing implementations. 

And given that it would be in core vs. userland, this would *not* apply: https://xkcd.com/927/

The one concern should be if there is anything about this RFC that would make writing such a shim impossible for any framework vendor?

> I think we shouldn't take over the naming of the super globals, e.g.
> $_GET really contains the query parameters and has nothing to do with
> GET or POST, so $request->getQueryParameter(...) would be a better
> name.

Please no. That is all too Java-esque verbosity.  

Very commonly used functionality can afford to be concise like $request->get() because it would be well-known and not have to compete with lots of other functionality for mindshare.  Thus no need for this to be so precise and have such long names when everyone writing PHP would soon lean what it means.

> I don't see any reason to keep specials such as
> $_SERVER['HTTP_X_REQUESTED_WITH'] vs. $request->requestedWith, which
> is just another HTTP header.

Reason: $request->requestedWith can be type-safe, something you asked for in another context.  

$_SERVER['HTTP_X_REQUESTED_WITH']  cannot be type safe without special cases in the language.

> The Request object should be mutable, e.g. you might want to change
> the client IP to be based on a x-forwarded-header instead of the TCP
> source address.

I totally agree it needs to be mutable, but only prior to first use.

After the first use having it be locked would gain us the benefits of robustness that immutability can provide.

-Mike

---

## #108518 — AllenJB — 2020-02-12T21:27:08+00:00

URL: https://externals.io/message/108436#108518 · In reply to: #108436

This might be more a "future scope" thing, but I would like to see a way 
to access the raw request body as part of this. Currently (as far as I 
know) the only way is to open/read php://input, which isn't particularly 
intuitive in my opinion.

AllenJB


> Hi Internals,
>
> After a couple of years of incubation, I am happy to offer a second version of this RFC:
>
>    https://wiki.php.net/rfc/request_response
>
> It proposes an object-oriented approach around request and response functionality already existing in PHP, in order to reduce the global-state problems that come with superglobals and the various response-related functions.
>
> The SQLite "about" page says, "Think of SQLite not as a replacement for Oracle but as a replacement for `fopen()`." <https://www.sqlite.org/about.html>  Likewise, think of this RFC not as a replacement for HttpFoundation or PSR-7, or as a model of HTTP messages, but as an object-oriented alternative to superglobals, `header()`, `setcookie()`, `setrawcookie()`, and so on.
>
> Thanks in advance for your time and consideration while evaluating it.

---

## #108520 — AllenJB — 2020-02-12T21:40:57+00:00

URL: https://externals.io/message/108436#108520 · In reply to: #108512

> Type Safety
>
> I think the API should be type safe. Currently $request->get['key']
> can be null | string | string[] | ... Most parameters only appear a
> single time, so a method returning the first parameter value or null
> could be used instead.

I may be misunderstanding what you're suggesting here, but it seems 
you're proposing to have ->get['key'] only return null|string, getting 
rid of the arrays of parameter values ( ?key[]=value1&key[]=value2 ) 
functionality here. (And I assume you intend the same for ->post['key'] )

If so, I would say this is a bad idea. I and a lot of other devs use 
this functionality frequently (more often in POST, but often enough in 
GET for purposes such as search pages). And how would multiple select 
inputs be handled?

AllenJB

---

## #108523 — Paul M. Jones — 2020-02-12T22:09:46+00:00

URL: https://externals.io/message/108436#108523 · In reply to: #108491

Hi Albert,

> 
> 
> > […]
> 
> That could be said for all INI settings: yes they can break things if you
> touch them without knowing what they do.
> 
> I think it might make sense to be able to disable superglobals and response
> functions if your codebase is committed to using the new classes, much like
> the old "register_globals" did. Why pollute the global namespace if you
> don't need them?

I share Harald's opinion here. I think a .ini setting to disable superglobals and the response-related functions is out-of-scope for this RFC.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #108524 — Paul M. Jones — 2020-02-12T22:46:22+00:00

URL: https://externals.io/message/108436#108524 · In reply to: #108518

Hi Allen & Robin,

Allen, you asked:

> 
> 
> This might be more a "future scope" thing, but I would like to see a way to access the raw request body as part of this. Currently (as far as I know) the only way is to open/read php://input, which isn't particularly intuitive in my opinion.


Robin asked the same thing earlier:

> 
> 
> What i haven't clearly seen in the RFC nor the interfaces of the proposed objects: how will this handle PUT / php:://input / raw posted data? Or am i missing something?

Answer: the php://input stream is accessible via the ServerRequest $content property; see <https://github.com/pmjones/ext-request#content-related>.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #108527 — Paul M.Jones — 2020-02-13T02:08:33+00:00

URL: https://externals.io/message/108436#108527 · In reply to: #108489

Hi Ben,


> 
> 
> Regarding the array of arrays for $accept* and $forwarded, what are your thoughts on using value objects with properties, rather than arrays with keys?

It's a fair suggestion, but I am not keen to expand the number of new declarations any more than necessary.

To play with your idea a little bit, let's say we start with ...

- ServerRequest
- ServerResponse
- ServerResponseSender

... then to bring in Jan Schneider's suggestion, we add ServerResponseInterface (4 classes).

Then we add the value objects themselves: ServerRequestAcceptValue and ServerRequestForwardValue. That's 6 classes.

That's maybe not so bad. But, once we start down this path, it's easy for me to imagine what comes after.

For example, since we're trying to do "the right thing," someone will suggest to typehint the properties "correctly." Instead of arrays of value objects, they probably ought to be collection objects. That gets us ServerRequestAcceptValueCollection and ServerRequestForwardValueCollection, and we're at 8 classes.

Then someone is likely to say that there ought to be interfaces for all those so their implementations can get swapped out. That's ... 

- ServerRequest
- ServerResponse
- ServerResponseInterface
- ServerResponseSender
- ServerRequestAcceptValue
- ServerRequestAcceptValueInterface
- ServerRequestAcceptValueCollection
- ServerRequestAcceptValueCollectionInterface
- ServerRequestForwardValue
- ServerRequestForwardValueInterface
- ServerRequestForwardValueCollection
- ServerRequestForwardValueCollectionInterface

... 12 classes and interfaces. And probably not done yet, once others really sink their teeth into it.

Now, that's not a *wrong* approach -- but it does seem like overkill to me.

Or, we could avoid starting down that path and stick with arrays, which in ServerRequest are read-only and immutable and get us all the things we actually need for our daily work here.

Of those two, I prefer the minimalist approach of arrays for this RFC; the "effort-to-benefit" ratio is much better.


-- 
Paul M. Jones
pmjones@pmjones.io
http://paul-m-jones.com

Modernizing Legacy Applications in PHP
https://leanpub.com/mlaphp

Solving the N+1 Problem in PHP
https://leanpub.com/sn1php

---

## #108529 — Ruud Boon — 2020-02-13T06:45:06+00:00

URL: https://externals.io/message/108436#108529 · In reply to: #108524

Hi!

I really like this RFC.
> 
> 
> Hi Allen & Robin,
> 
> Allen, you asked:
> 
> > […]
> 
> 
> Robin asked the same thing earlier:
> 
> > […]
> 
> Answer: the php://input stream is accessible via the ServerRequest $content property; see <https://github.com/pmjones/ext-request#content-related>.
In the the RFC I see that $content will return  php://input <php://input> using file_get_contents on the fly. Can we add the possibility to get a reference to the stream as well? This allows the use of stream_copy_to_stream, mime_content_type etc without reading the fill input to memory.

> 
> 
> --
> Paul M. Jones
> pmjones@pmjones.io
> http://paul-m-jones.com
> 
> Modernizing Legacy Applications in PHP
> https://leanpub.com/mlaphp
> 
> Solving the N+1 Problem in PHP
> https://leanpub.com/sn1php
> 
> --
> 
> 
Cheers,
Ruud

---

## #108534 — come.chilliet@fusiondirectory.org — 2020-02-13T10:52:45+00:00

URL: https://externals.io/message/108436#108534 · In reply to: #108512

Le mercredi 12 février 2020, 19:20:56 CET Niklas Keller a écrit :
> Naming
> 
> I think we shouldn't take over the naming of the super globals, e.g.
> $_GET really contains the query parameters and has nothing to do with
> GET or POST, so $request->getQueryParameter(...) would be a better
> name.

I think this remark is really on point.
GET and POST are HTTP methods and not ways of passing data. You can have query parameters on any request, and you can have POST data with a lot of other HTTP methods, as is commonly used in REST APIs.

I do not like the name getQueryParameter at first sight, but I do not like get() and post() for getting values from $_GET and $_POST.
I would expect a method named post to actually post something, not just get a value.

-- 
Côme Chilliet
FusionDirectory - https://www.fusiondirectory.org

---

## #108535 — Ekin B. — 2020-02-13T11:23:20+00:00

URL: https://externals.io/message/108436#108535 · In reply to: #108534

Hi all,

> 
> 
>  
> Le mercredi 12 février 2020, 19:20:56 CET Niklas Keller a écrit :
> > […]
> 
> I think this remark is really on point.
> GET and POST are HTTP methods and not ways of passing data. You can have query parameters on any request, and you can have POST data with a lot of other HTTP methods, as is commonly used in REST APIs.
> 
> I do not like the name getQueryParameter at first sight, but I do not like get() and post() for getting values from $_GET and $_POST.
> I would expect a method named post to actually post something, not just get a value.
> 
> -- 
> Côme Chilliet
> FusionDirectory - https://www.fusiondirectory.org
> 
> --

I agree that this is indeed on point.
Personally I would like $request->getQueryParameter() and $request->getBody() over $request->get() and $request->post().
In the former case you are asking for the parameters in the query string (query component of the URI) and the latter is to get the request body. These method names make it very clear what you're asking for.

What kind of bothers me in general about this RFC is that... we are talking about Request and Response and these are standard HTTP components, yet the RFC is about providing wrappers for existing global PHP variables and functions. It does not try to model these components as they are in their standard, nor aim to do so.

This is why I believe it's better to leave it to userland implementations. Besides the fact that they are widely adopted, they attempt to follow the specification they are providing. 

Regards,
Ekin H. Bayar 
https://ekins.space 
https://heap.space

---

Next page: https://externals.io/message/108436.md?page=2
