klein / klein.php

A fast & flexible router
MIT License
2.66k stars 290 forks source link

DISPATCH_CAPTURE_AND_RETURN returns null #272

Closed steadweb closed 9 years ago

steadweb commented 9 years ago

Is this done by design?

IMO I'd expect the output of the response to be returned, so I can easily assign that to a variable and do something with it. Example:

$klein = new \Klein\Klein();

$klein->respond('GET', '/hello-world', function () {
    return 'Hello World!';
});

$message = $klein->dispatch();

echo $message; // Hello World!

The switch statement / line can be found here:

https://github.com/chriso/klein.php/blob/master/src/Klein/Klein.php#L645

As you can see, buffered_content is assigned but set to null, then is returned without even assigning the response body.

steadweb commented 9 years ago

Locally I've changed the switch statement to return the contents of the closure. If this is acceptable I can submit a PR.

...
case self::DISPATCH_CAPTURE_AND_RETURN:
    $buffed_content = null;
    if (ob_get_level()) {
        $buffed_content = $this->response->body();
    }
    return $buffed_content;
    break;
Rican7 commented 9 years ago

Yes, that is by design. I think you might be misunderstanding the dispatch control constants... which is most likely my fault for not better documenting them. :/

The dispatch constants are all about controlling output buffering. The DISPATCH_CAPTURE_AND_RETURN constant, in particular, functions in exactly the way that it describes: During the dispatch process, any output that is generated (using echo or any other standard out functions) is caught in a buffer and then returned to the caller of the dispatch() method.

These constants and their behaviors don't operate on the response body. That is easily retrieved and settable by a user with a simple $klein_instance->response()->body() call. Instead, these constants exist for a way to control the raw output, so that headers can be properly set without worrying about output already reaching the HTTP client.

Make sense?

steadweb commented 9 years ago

Thanks @Rican7 - it does make sense. Accessing the response through the $klein instance works as expected.

Rican7 commented 9 years ago

Awesome! I'm glad I could help! :smiley: