Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Request and response

A request is everything the browser sent: the address, parameters, form fields. A response is what the site sends back: a page, a redirect or data. In a controller they are available as $this->request and $this->response; there is no need to create them.

Address parameters

// src/Controller/ArticlesController.php
public function index(): void
{
    $search = $this->request->getQuery('q');
 
    $this->set('search', $search);
}

getQuery() reads a parameter after the question mark. For the address /articles?q=php the $search variable gets the string php, and null when the parameter is absent.

Default value

$page = (int) $this->request->getQuery('page', 1);

The second argument is returned when the address has no such parameter. Values from the address always arrive as strings, so a number is cast explicitly.

Form fields

public function add(): void
{
    if ($this->request->is('post')) {
        $title = $this->request->getData('title');
        $all = $this->request->getData();
    }
}

is('post') checks that a form was submitted. getData('title') returns one field, and getData() without arguments returns an array of all fields.

What else the request has

CallWhat it returns
getQuery('q')An address parameter
getData('title')A form field
getParam('controller')A part of the route: controller, action
is('post'), is('ajax')A check of the request kind
getHeaderLine('User-Agent')A request header
clientIp()The visitor's address

Redirect

public function old()
{
    return $this->redirect(['action' => 'index']);
}

redirect() sends the browser to another page. The address is given as an array, as in routes: here a visitor of /articles/old ends up on /articles. A string works too: $this->redirect('/').

JSON response

public function count()
{
    $data = ['count' => 3];
 
    return $this->response
        ->withType('application/json')
        ->withStringBody(json_encode($data));
}

When an action returns a response, no template is rendered. At /articles/count the browser shows {"count":3}. The status code is changed with withStatus(404).

Restricting the method

public function delete(int $id)
{
    $this->request->allowMethod(['post', 'delete']);
 
    // delete the record
 
    return $this->redirect(['action' => 'index']);
}

allowMethod() rejects a request with any other method with a 405 error. This way an action that changes data cannot be called by a plain link.

Common mistake

$this->redirect(...) without the word return does not stop the action: the code below keeps running, and a record may be saved or deleted although the visitor has already been sent to another page. Always write return $this->redirect(...).

Thanks for reading!

Donate to the site — we work hard for you.