REMEMBER PHP

MINTE9
2REMEMBER




Last update:   23-07-2021

Introduction

Why would you want to create your own framework? ! To learn more about the low level arhitecture of modern web frameworks. To learn and experiment for fun (learn and throw approach). To refactor and old app that needs recent best practices.

Pattern

Following the MVC pattern is not the right goal. The main goal should be Separartions of Concerns. The framework you are creating will be a HTTP framework or Request/Response framework.

Without Framework

 CodeCopy
// index.php

$name = $_GET['name'];
printf("Hello %s", $name);
... 3 lines
˄˄˄
 
http://tests.local/php/framework/index.php?name=Fabian
    // Hello Fabian
... 2 lines
˄˄˄
Fix php warning
 
http://tests.local/php/framework/index.php
    // Notice: Undefined index: name
... 2 lines
˄˄˄
 CodeCopy
// index.php

$name = $_GET['name'] ?? "World";
printf("Hello %s", $name);
... 3 lines
˄˄˄
 
http://tests.local/php/framework/index.php
    // Hello World
... 2 lines
˄˄˄
Fix vulnerability XSS - Cross Site Scripting
 
http://tests.local/php/framework/index.php?name=<script>alert("Hack!");</script>
    // alert: Hack!
... 2 lines
˄˄˄
 CodeCopy
// index.php

$name = $_GET['name'] ?? "World";
header('Content-Type: text/html; charset=utf-8');
printf("Hello %s", htmlspecialchars($name, ENT_QUOTES, 'UTF-8'));
... 4 lines
˄˄˄
 
http://tests.local/php/framework/index.php?name=<script>alert("Hack!");</script>
    // Hello <script>alert("hack!");</script>
... 2 lines
˄˄˄
! As you can see this simple code is not that simple anymore. Also, this code can be complex to test, here is a tentative PHPUnit test for this code:
 CodeCopy
// test.php

use PHPUnit\Framework\TestCase;

class IndexTest extends TestCase
{
    public function testHello()
    {
        $_GET['name'] = "Fabian";

        ob_start(); // not naturaly and ugly
        include "index.php";
        $content = ob_get_clean();

        $this->assertEquals("Hello Fabian", $content);
    }
}
... 13 lines
˄˄˄
 
// terminal

cd /var/www/tests.local/php/framework

composer require --dev phpunit/phpunit ^8

./vendor/bin/phpunit test.php
... 4 lines
˄˄˄
Framework v1.0
Questions    
No. 85   Foundation
CARD
84

        A B C D E F
🔔
1/2