taniarascia / laconia

🏺 ‎ A minimalist MVC framework.

Home Page:https://laconia.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Separate server response from controllers

halfer opened this issue · comments

commented

Continuing on my theme of testability, another item to think about and possibly implement. Your controllers will do one of two things:

  • Echo HTML to standard output
  • Use header() to perform a redirect and exit

I would suggest that instead you:

  • Return a Laconia\WebResponse object

You can call this whatever you like, but to wire it in, I'd do this in your controller:

public function setWebResponse(Laconia\WebResponse $webResponse) {
    $this->webResponse = $webResponse;
}

I'd then modify view to inject the HTML it generates into the WebResponse (to capture HTML in a variable rather than printing it immediately, use output buffering).

The web response could look a bit like this:

namespace Laconia;

class WebResponse {
    protected $isOutput = false;
    protected $isRedirect = false;
    protected $output;
    protected $redirect;

    public function setOutput($output) {
        $this->isOutput = true;
        $this->output = $output;
    }

    public function setRedirect($redirect) {
        $this->isRedirect = true;
        $this->redirect = $redirect;
    }

    public function execute() {
        if ($this->isOutput) {
            echo $this->output;
        } elseif ($this->isRedirect) {
            header($this->redirect);
        }
    }
}

Woop! That is much better for testing. It is, specifically, better for mocking, so we can pass a fake object during testing, to see what things get called on it.

I'm going to close these tickets and handle any testing related optimizations in the testing issue.

commented

No worries. I think I might have promised to do some examples, and never got around to it - if so, apologies! I promise more than my time management skills will allow ;-)

Hope your current projects are going well.

Haha, no worries! I appreciated the input and help. I've just shifted my focus to other projects and don't think I'll get around to those optimizations so it was better to close them.

commented

No problem. I am still doing PHP, but I am trying to learn JavaScript now. I'm building a little microservices project with React and Express, and there is fair bit to juggle...