PROGRAMMING

m9/ PHP
REMEMBERS




Last update:   23-07-2021

HTTP Foundation

Web code is about interacting with HTTP. The fundamental principles of our framework should be around HTTP specification. ! The request is represented by global variables ($_GET, $_POST, ...). The response is generated by functions (echo, header, setcookie, ...)

Component

Symfony HttpFoundations replaces those variables and functions with an OOP layer. To use this component, add it as a dependency of the project. ! When installing a new dependency Composer generates vendor/autoload.php Without autoloading you will need to include every file before using it.
 
// terminal

composer require symfony/http-foundation

Foundation

The createFromGlobals() creates a Request object from PHP global variables. The send() method sends the Response object back to the client.
 
// index.php

require_once __DIR__.'/vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$request = Request::createFromGlobals();
$name = $request->get('name', 'World');

$response = new Response(sprintf('Hello %s', 
    htmlspecialchars($name, ENT_QUOTES, 'UTF-8')));
$response->send();
... 3 lines
 
 
http://tests.local/php/framework/ 
    // Hello World

http://tests.local/php/framework/index.php?name=Fabian 
    // Hello Fabian

Request

Now you have all the request information.
 
$request->getPathInfo(); // URI requested
$request->query->get('foo'); // GET variables
$request->request->get('bar'); // POST variables
$request->server->get('HTTP_HOST'); // SERVER variables
$request->files->get('foo'); // UPLOADED file
$request->cookies->get('PHPSESID'); // COOKIES
$request->headers->get('host'); // HTTP request header
$request->headers->get('content-type'); 
$request->getMethod(); // GET, POST, PUT, DELETE, HEAD
... 3 lines
 

Response

! With a HttpFoundation component ... you can simulate a response.
 
// index.php

require_once __DIR__.'/vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$response = new Response();
$response->setContent("Hello Symfony");
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/html');

$response->send();
... 3 lines
 
 
http://tests.local/php/framework/index2.php 
    // Hello Symfony

Advantages

! The component have been audited for security issues by an independent company. Many other developers have read the code and fixes potential security problems. The component allows you to write code and tests faster. It allows a better interoperability between all frameworks (Symfony, Laravel, ...). Framework v1.2
Questions    
Front

        A B C D E F
🔔
1/4