PHP, Deeper

7.3

April 2019

By Loïc Truchot

PHP: Hypertext Processor

-> PHP: Hypertext Processor

-> PHP: Hypertext Processor

-> PHP: Hypertext Processor

-> PHP: Hypertext Processor

-> PHP: Hypertext Processor

-> PHP: Hypertext Processor

-> PHP: Hypertext Processor

-> PHP: Hypertext Processor

-> PHP: Hypertext Processor

Better debugging

  • bugs
    • are inherent in coding
    • more frequent in interpreted languages (PHP)
    • more frequent in loosely typed language (PHP)
    • not related to experience
  • tools
    • Best practices
    • A good IDE (linters, prettiers)
    • var_dump & XDebug
    • RTFM (& Errors !)
    • Debuggers
# php.ini
zend_extension=""
xdebug.default_enable=1
xdebug.auto_trace=1
xdebug.profiler_enable=1

Variables Scope

JavaScript

VS

PHP

<script>
    var test = 42;
    function modifyTest () {
        test = 24;
    }
    modifyTest()
    console.log(test);
</script>
<?php
    $test = 42;
    function modifyTest () {
        $test = 24;
    }
    modifyTest();
    var_dump($test);
?>

Who will win ?

step 1

Variables Scope

step 2

  • scope (or lexical scope) is "where can I use my variable ?"
  • answer is different for each language
  • In PHP, the scope of a variable is
    • the function, where the variable is declared (local)
      • OR
    • everywhere, except in functions (global)
$test = 42;
function testX3 ($val) {
    $result = $val * 3;
    return $result;
}
$test = testX3($test);
  • a function is like a mini-program, with its own variables
  • use values in a function ? give it as arguments, and I return the modified value !

Workshop Session

scope

  • write a function useful to enhance a pizza
    • it takes a pizza hashtable with ingredients
    • it return an enhanced hashtable
      • ​if there is some "ham" or "chicken", it add "veg" => false
      • else, "veg" => true

Variables Scope

step 3

  • access a global variable if a function ?
    • add "global $a, $b;" at the beginning of the function
$test = 42;
function testX4 () {
    global $test;
    $test = $test * 4;
}
testX4();
var_dump($test);
  • so it modify something outside the function
  • it's called a side effect
  • it's bad and you should feel bad
$test = 42;
function testX5 (&$var) {
    $var = $var * 4;
}
testX5($test);
var_dump($test);
  • you can achieve the same with reference "&"
  • value vs reference is a larger purpose
  • it is a bad practice too, called "impure function"

Workshop Session

scope

  • use your pizza vegetarian enhancer with a global
  • use your pizza vegetarian enhancer with a reference
  • add a "vegan" tag for pizza without meat and cheese (FizzBuzz)
  • in the "foreach" displaying pizzas :
    • display a bootstrap badge for every vegetarian pizza
    • display a bootstrap badge for every vegan pizza

To remember

  • scope is related to the life cycle of a variable
    • when & where it was born
    • when & where it is usable
    • when & where it will die
  • in PHP, the scope is the function:
    • variables can have the same name in/out a function, because it will not be the same variable 
  • you can access global scope (global or &), but it is dangerous
    • side effects are out of contol
    • side effects are not testables
  • scope is different regarding programming languages: have to learn it

include / require

  • Your code needs to be organized
  • between 100 and 500 lines
  • how to organize it ?
    • one function per file ?
    • one class per file ?
    • one collection per file ?
    • one template
  • include or require ?
  • include_once or require_once ?

Workshop Session

inclusion

  • reorganize the code of our pizzeria
    • one folder for templates, on for functions, one for data
    • one file for all collections, "require_once"
    • one function per file loaded with a "require_once"
    • one template per file, by big parts, loaded with include
    • what happen if we load several time the same file ?
    • add some beautiful responsive structure for site

To remember

  • every language have an import/export system
  • PHP offers
    • include, to import one or more time, warning any error
    • include_once to import only one time, warning any error
    • require, to import one or more time, error crashing
    • require_once, to import only one time, error crashing
  • Warning: PHP imports are as it comes, without dependency injection: everything should be logical, well organized, well documented

superglobales

  • as well as functions, some native globales exists
    • $GLOBALS: I already know that
    • $_REQUEST, $_GET, $_POST,  $_FILES for web requests & forms inputs
    • $_SERVER & $_ENV for infos about computer that run PHP
    • $_SESSION & $_COOKIE to store infos about users

 

@see https://www.php.net/manual/fr/language.variables.superglobals.php

Workshop Session

superglobales

  • try to var_dump some globals: comment the result
  • add this code to your html in superglobales.php
<form action="superglobales.php" method="POST">
    Name: <input type="text" name="name" />
    <input type="submit" />
</form>
  • in the same file, display $_POST, and play with the input field. What does it implied ?

forms and $_POST

  • some words about HTTP protocol & methods
    • POST, GET, PUT, DELETE... + PATCH & HEAD
  • HTML forms are dedicated to this kind of communication
  • GET for url params
  • POST for payloads
  • every data will be in $_POST array, but sometimes formatted (checkbox = "on" || "off")

Workshop Session

forms

  • create a page dedicated to register our user
  • name field is required
  • when user is registered, say hello and list all infos in an HTML table

Workshop Session

forms

  • create a hangman game
    • use HTML hidden inputs
    • use PHP function: strpos, str_split, join

AJAX

  • functions are useful to do some input / output (i/o)
  • input are often coming from user prompts/forms
  • AJAX is the best way to get a user input

step 1

function toQuizz($quizz, $rightIndex, $userChoice) {
    if ($quizz[$rightIndex] == $userChoice) {
        return "bravo";
    } else {
        return "error: right answer was" . $quizz[$rightIndex];
    }
}

AJAX

  • to do some AJAX, we need
    • a php file, that will manage the request
    • a javascript library that can do some ajax
    • a form

step 2

$("#btn").click(event => {
	$.post({ 
		url: "request.php",
		data: { name: $("#ipt").val() },
		success: data => alert(data)
	});
});	
<?php 
	$name = $_POST["name"];
	echo "coucou $name !"
?>

Live coding session

AJAX

  • finaliser le quizz pour qu'il marche avec AJAX
  • travailler sur un panier pour notre pizzeria

RegExp

  • rational expressions / regular expression: the nightmare begin
  • what about a if to check an  email ?
  • how to do that in one line ? the RegExp !
  • a lot of string native functions in php: use them
  • preg_match($pattern, $str): check if string valid the condition
<?php
$containTest = preg_match("/test/", "ceci est un test.");
var_dump($containTest);
?>

Live Coding Session

regexp

  • validate email in our register form
  • is it possible with AJAX ?

other topics

  • files
  • session
  • mails et notifications
  • database & PDO

THANK'S EVERYONE
It's finally done ! See you soon

Next chapter : Oriented Object PHP... 

Deeper PHP

By Loïc TRUCHOT

Deeper PHP

  • 285