Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Request data

A request is everything the browser sent to the server: the address, parameters after the question mark, form fields, headers. A controller reads this data in two ways: with the short params() plugin and through the request object, getRequest(). Both are available in any action; there is nothing to create.

A parameter from the address

Route parameters, written with a colon in the configuration, are read by fromRoute():

// module/Blog/src/Controller/PostController.php
public function viewAction()
{
    $id = (int) $this->params()->fromRoute('id');
 
    return new ViewModel(['id' => $id]);
}

At /blog/5 the $id variable holds the number 5. A value from the address is always a string, so it is cast to an integer.

The query string

Parameters after the question mark are read by fromQuery(). The second argument is the value used when the parameter is missing:

public function indexAction()
{
    $page = (int) $this->params()->fromQuery('page', 1);
    $search = (string) $this->params()->fromQuery('q', '');
 
    return new ViewModel(['page' => $page, 'search' => $search]);
}

For /blog?page=2&q=php you get $page equal to 2 and $search equal to php. For /blog — 1 and an empty string.

All params methods

MethodWhere the value comes from
fromRoute('id')A route parameter
fromQuery('page', 1)The query string after ?
fromPost('title')A field of a form sent with POST
fromFiles('image')An uploaded file
fromHeader('User-Agent')A request header (a header object)

A call without a name — for example fromQuery() — returns all values as an array.

The request object

When you need the request method or all form data at once, use getRequest():

public function addAction()
{
    $request = $this->getRequest();
 
    if ($request->isPost()) {
        $data = $request->getPost()->toArray();
 
        // $data['title'], $data['body']
    }
 
    return new ViewModel();
}

The add action answers both opening the page (GET) and submitting the form (POST). isPost() tells the two cases apart.

MethodWhat it returns
isGet(), isPost()Whether the request method matches
getPost('title')One form field
getPost()->toArray()All form fields
getQuery('page', 1)A query string parameter
isXmlHttpRequest()Whether the request was sent from JavaScript

Common mistake

Request data cannot be trusted to be correct. The value of fromQuery('page') may be text, a negative number or missing. Cast types — (int), (string) — and set a default value, and check form data with the rules covered in the validation lesson.

Thanks for reading!

Donate to the site — we work hard for you.