Skip to content

ch03_controllers

Daniel Samson edited this page Jan 18, 2024 · 4 revisions

Teensy PHP offers some basic functions to control the way your application operates.

You may need to control your application based on a header such as the User Agent header:

$header = request_header(string $header);

You can also set the response header:

response_header(string $header, string $value);

To filter based on the Accept header:

accept(string $content_type): bool

To send a response to the client you can render an output:

render(int $http_code, string $content, array $headers): void

To control the content type header:

content(string $type, string $content): string

To respond with HTML content:

html_out(string $content): string

To redirect the client to an other url:

redirect(string $url)

JSON API

When creating an API, you will need to get JSON posted in the body of the request:

$body = json_in() : array

To output JSON content:

json_out(array $array): string

Content Types

TeensyPHP also provides the following pre-defined constants for the content type:

content(ATOM_CONTENT, $content);
content(CSS_CONTENT, $content);
content(JAVASCRIPT_CONTENT, $content);
content(JSON_CONTENT, $content);
content(PDF_CONTENT, $content);
content(TEXT_CONTENT, $content);
content(HTML_CONTENT, $content);
content(XML_CONTENT, $content);

Router Example

// index.php
route(method(GET), url_path("/"), function() {
    if (accept(JSON_CONTENT)) {
        // handle json api client
        render(200, json_out(["hello" => "world"]));
        return;
    }
    
    if (accept(HTML_CONTENT)) {
        // handle html client
        render(200, html_out(template(__DIR__."/template/home.php", [])));
        return;
    }

    throw new Exception("Not Acceptable", 406);
});

route(method(POST), url_path("/echo"), function() {
    if (accept(JSON_CONTENT)) {
        $body = json_in();
        // do something with body ...
        render(200, json_out(["hello" => "world"]));
        return;
    }
   
    throw new Exception("Not Acceptable", 406);
});

route(method(GET), url_path("/site.css"), function() {
    render(200, content(CSS_CONTENT, file_get_contents(__DIR__.'/assets/site.css')));
});
Clone this wiki locally