vlucas / bulletphp

A resource-oriented micro PHP framework
http://bulletphp.com
BSD 3-Clause "New" or "Revised" License
416 stars 50 forks source link

Add headers before response content is set #50

Closed seblucas closed 6 years ago

seblucas commented 10 years ago

Hi again,

I'm adding paging to my Rest API based on bullet and I'd like to add some headers (X-Total-Count and Link).

Judging by the first lines of function header in response.php adding headers is impossible if the response has no content. Is there a reason why ?

For now I'm storing the content of my two headers in my $app ($app["X-Total-Count"] and $app["Link"]) and I add the headers in my response handler. It does not feel right even if it works without too much work. See below

Do you see a better solution ?

Thanks in advance.

seblucas commented 10 years ago

I'm now using a MetadataContext class and it feels right but my first question remains

vlucas commented 10 years ago

Seems like you should be able to set headers before sending a response - that definitely breaks my expectations as well. I won't have a chance to dig into this for another few days, but this definitely seems like a bug.

seblucas commented 10 years ago

Thanks for the answer. Take your time ;)

acicali commented 9 years ago

Judging by the first lines of function header in response.php adding headers is impossible if the response has no content. Is there a reason why ?

I don't believe this is the case. The $content parameter is meant to accept the value of the header, not the response body. The first few lines of Response->header() are checking to see if a value was provided, and if not, it returns the value of that header (or false if it hasn't been set). In this way, the header() function acts as a setter() and getter(), which is a common pattern.

Example:

$response->header('X-Total-Count', 20); //set the 'X-Total-Count' header

$total = $response->header('X-Total-Count'); //returns '20'

The third parameter specifies what the setter() should do if the header already exists (true replaces it, false duplicates it).

Please issue lashings if I'm incorrect. :)

acicali commented 9 years ago

Aww :(

In App->run(), the App->response() is overwritten. It seems custom response headers are not possible with Bullet.

vlucas commented 9 years ago

This is a huge issue. Custom headers should absolutely be possible. I will look into this very soon.

acicali commented 9 years ago

I shouldn't have said "not possible". One can simply use the native PHP header() function before sending any output.

More accurately, it appears _to me_ that Response->header() cannot be used to send custom response header.

netom commented 6 years ago

Solved, see AppTest::testSupportCustomHeaders(). Commit b4b1dd7 make Response::content() fluent, and makes it easy to build and return a response in a single expression.