The New Myth family: SprintPHP Bonfire Practical CodeIgniter 3

New Myth Media Blog

Serving the New Myth Media Family.

Practical CodeIgniter 3 Released

My new book about making the most of CodeIgniter 3 is out!

One of the biggest changes, conceptually, in CodeIgniter 4 is the way that Input and Output is handled. In prior versions, including the latest v3 releases, Input and Output were handled as two classes that contained mostly related functionality. There wasn't any "grand scheme" behind it, but it still worked pretty nicely. In v4, though, we've modeled the HTTP layer much more closely, building a new hierarchy of classes to represent the common HTTP requests and responses.

At A Glance

When working with web applications - as opposed to CLI-only services - you'll really just need to worry about two classes: IncomingRequest and Response.

IncomingRequest

The IncomingRequest class provides access to the HTTP request and all of the side data that comes with it, including:

  • GET, POST, SERVER, and ENV variables
  • Headers
  • Cookies
  • the URL object that is currently being looked at
  • uploaded files

and provides convenience methods for things like:

  • client IP Address
  • is it an AJAX request?
  • is it a CLI request?
  • is it over HTTPS?

If you're wondering about the difference in naming, and, "Shouldn't IncomingRequest be simply Request?" the answer is nope. There already is another Request class that is more generic and doesn't know the details of an HTTP request, which contains all of the fun stuff like GET and POST vars. A Request can be one of two things: either the request that a client browser has made to the server (incoming); or a request that you are sending out to an external server, (outgoing).

Response

The response class is what you work with to build your response to the client. You can assign headers, set the output directly, and more. It provides convenience methods for things like:

  • setting appropriate no-cache headers
  • working with HTTP cache headers
  • redirecting to a new page

A Quick Example

This may sound like it's going to be pretty technical to work with, but it's really not. The controller already has an instance of the classes as properties, but for simple work, you'll never even need to use them. Any output from the controller is captured and automatically set as the body of the Response. A Hello World example might look like this:

class Home extends \CodeIgniter\Controller
{
    public function index()
    {
        echo "Hello World!";
    }
}

Easy, peasy.

What this does do, though, is provide you the ability to really dig in and fine-tune the response if you need to. You can create with complex HTTP caching strategies, work with the IncomingRequest to tailor your response through Content Negotiation, and much more.

Here's a slightly more involved example, though you'll see it's all easily readable, and simple to work with.

class Home extends \CodeIgniter\Controller
{
    public function __construct(...$params)
    {
        parent::__construct(...$params);

        // This controller is only accessible via HTTPS
        if (! $this->request->isSecure())
        {
            // Redirect the user to this page via HTTPS, and set the Strict-Transport-Security
            // header so the browser will automatically convert all links to this page to HTTPS
            // for the next year.
            force_https();
        }
    }

    public function index()
    {
        $data = [
            ...
        ];

        // Set some HTTP cache rules for this page.
        $this->response->setCache([
            'max-age' => 300,
            's-max-age' => 900,
            'etag' => 'foo'
        ]);

        // Return JSON
        $this->response->setContentType('application/json')
                       ->setOutput(json_encode($data));
    }
}

In this example, we've done three primary things. First, we forced this page to be accessed via HTTPS by both a redirect to the HTTPS version of the current URL, and by setting a Strict-Transport-Security header, which is supported by most of the major browser vendors and lets the browser convert the URL to HTTPS automatically before ever sending the request. Second, we're setting some HTTP cache rules to help the browser know when it can reuse data it already has and when it can't, which means fewer HTTP requests, never hitting the server, and increasing performance to boot. Finally, we're outputting some JSON data to the user, ensuring that the correct content type is set.

Hopefully, this helps to get a glimpse at the future of CodeIgniter, and realize that change doesn't always have to be scary :) More articles will come in the future talking about the concepts of the framework as more and more parts are pinned down to a fairly stable place.