DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Combining gRPC With Guice
  • Chain of Responsibility In Microservices
  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test
  • Scalable Support Request Analysis Using Embeddings, HDBSCAN, and Tiny LLMs

Trending

  • Prompt Injection Is Real, So I Built a Python Firewall for LLM Pipelines
  • Operationalizing Enterprise AI at Scale: Architecture, Governance, and Adoption
  • A Spring Boot App With Half the Startup Time
  • The Big Data Architecture Blueprint: Core Storage, Integration, and Governance Patterns
  1. DZone
  2. Coding
  3. Languages
  4. Working with Request objects in PHP

Working with Request objects in PHP

By 
Gonzalo Ayuso user avatar
Gonzalo Ayuso
·
Oct. 18, 11 · News
Likes (0)
Comment
Save
Tweet
Share
9.3K Views

Join the DZone community and get the full member experience.

Join For Free

normally when we work with web applications we need to handle request objects. requests are the input of our applications. according to the golden rule of security:

filter input-escape output


we cannot use $_get and $_post superglobals. ok we can use then but we shouldn’t use them. normally web frameworks do this work for us, but not all is a framework.

recently i have worked in a small project without any framework. in this case i also need to handle request objects. because of that i have built this small library. let me show it.

basically the idea is the following one. i want to filter my inputs, and i don’t want to remember the whole name of every input variables. i want to define the request object once and use it everywhere. imagine a small application with a simple input called param1. the url will be:

test1.php?param1=11212

and we want to build this simple script:

echo "param1: " . $_get['param1'] . '<p/>';

the problem with this script is that we aren’t filtering input. and we also need to remember the parameter name is param1. if we need to use param1 parameter in another place we need to remember its name is param1 and not param1 or para1. it can be obvious but it’s easy to make mistakes.

my proposal is the following one. i create a simple php class called request1 extending requestobject object:

example 1: simple example

class request1 extends requestobject
{
    public $param1;
}

now if we create an instance of request1, we can use the following code:

$request = new request1();
echo "param1: " . $request->param1 . '<p/>';

i’m not going to explain the magic now, but with this simple script we will filter the input to the default type (string) and we will get the following outcomes:

test1.php?param1=11212
param1: 11212

test1.php?param1=hi
param1: hi

maybe is hard to explain with words but with examples it’s more easy to show you what i want:

example 2: data types and default values

class request2 extends requestobject
{
    /**
     * @cast string
     */
    public $param1;
    /**
     * @cast string
     * @default default value
     */
    public $param2;
}

$request = new request2();

echo "param1: <br/>";
var_dump($request->param1);
echo "<br/>";

echo "param2: <br/>";
var_dump($request->param2);
echo "<br/>";

now we are will filter param1 parameter to string and param2 to string to but we will assign a default variable to the parameter if we don’t have a user input.

test2.php?param1=hi&param2=1

param1: string(2) "hi"
param2: string(1) "1"

test2.php?param1=1&param2=hi

param1: string(1) "1"
param2: string(2) "hi"

test2.php?param1=1
param1: string(1) "1"
param2: string(13) "default value"

example 3: validadors

class request3 extends requestobject
{
    /** @cast string */
    public $param1;
    /** @cast integer */
    public $param2;

    protected function validate_param1(&$value)
    {
        $value = strrev($value);
    }

    protected function validate_param2($value)
    {
        if ($value == 1) {
            return false;
        }
    }
}
try {
    $request = new request3();

    echo "param1: <br/>";
    var_dump($request->param1);
    echo "<br/>";

    echo "param2: <br/>";
    var_dump($request->param2);
    echo "<br/>";
} catch (requestobjectexception $e) {
    echo $e->getmessage();
    echo "<br/>";
    var_dump($e->getvalidationerrors());
}

now a complex example. param1 is a string and param2 is an integer, but we also will validate them. we will alter the param1 value (a simple strrev ) and we also will raise an exception if param2 is equal to 1

test3.php?param2=2&param1=hi
param1: string(2) "ih"
param2: int(2)

test3.php?param1=hola&param2=1
validation error
array(1) { ["param2"]=> array(1) { ["value"]=> int(1) } }

example 4: dynamic validations

class request4 extends requestobject
{
    /** @cast string */
    public $param1;
    /** @cast integer */
    public $param2;
}

$request = new request4(false); // disables perform validation on contructor
                               // it means it will not raise any validation exception
$request->appendvalidateto('param2', function($value) {
        if ($value == 1) {
            return false;
        }
    });

try {
    $request->validateall(); // now we perform the validation

    echo "param1: <br/>";
    var_dump($request->param1);
    echo "<br/>";

    echo "param2: <br/>";
    var_dump($request->param2);
    echo "<br/>";
} catch (requestobjectexception $e) {
    echo $e->getmessage();
    echo "<br/>";
    var_dump($e->getvalidationerrors());
}

more complex example. param1 will be cast as string and param2 as integer again, same validation to param2 (exception if value equals to 1), but now validation rule won’t be set in the definition of the class. we will append dynamically after the instantiation of the class.


test4.php?param1=hi&param2=2
param1: string(4) "hi"
param2: int(2)

test4.php?param1=hola&param2=1
validation error
array(1) { ["param2"]=> array(1) { ["value"]=> int(1) } }

example 5: arrays and default params

class request5 extends requestobject
{
    /** @cast arraystring */
    public $param1;

    /** @cast integer */
    public $param2;

    /**
     * @cast arraystring
     * @defaultarray "hello", "world"
     */
    public $param3;

    protected function validate_param2(&$value)
    {
        $value++;
    }
}

$request = new request5();

echo "<p>param1: </p>";
var_dump($request->param1);

echo "<p>param2: </p>";
var_dump($request->param2);

echo "<p>param3: </p>";
var_dump($request->param3);

now a simple example but input parameters allow arrays and default values.

test5.php?param1[]=1&param1[]=2&param2[]=hi
param1: array(2) { [0]=> int(1) [1]=> int(2) }
param2: int(1)
param3: array(2) { [0]=> string(5) "hello" [1]=> string(5) "world" }

test5.php?param1[]=1&param1[]=2&param2=2
param1: array(2) { [0]=> string(1) "1" [1]=> string(1) "2" }
param2: int(3)
param3: array(2) { [0]=> string(5) "hello" [1]=> string(5) "world" }

requestobject

the idea of requestobject class is very simple. when we create an instance of the class (in the constructor) we filter the input request (get or post depending on request_method) with filter_var_array and filter_var functions according to the rules defined as annotations in the requestobject class. then we populate the member variables of the class with the filtered input. now we can use to the member variables, and auto-completion will work perfectly with our favourite ide with the parameter name. ok. i now. i violate encapsulation principle allowing to access directly to the public member variables. but imho the final result is more clear than creating an accessor here. but if it creeps someone out, we would discuss another solution :) .

full code here on github

what do you think?


Requests PHP Object (computer science)

Published at DZone with permission of Gonzalo Ayuso. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Combining gRPC With Guice
  • Chain of Responsibility In Microservices
  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test
  • Scalable Support Request Analysis Using Embeddings, HDBSCAN, and Tiny LLMs

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook