Fix typos

This commit is contained in:
Marcello 2021-09-20 19:35:32 +02:00
parent 76550dfa3c
commit 5c0799df7f
118 changed files with 1150 additions and 1602 deletions

View file

@ -13,13 +13,13 @@ function autoloader($class) {
# __DIR__ -> path of calling file
# $class -> className (hopefully same as file)
# if class is in namesapce $class -> Namespace\className (hopefully folders mirror Namespace)
# if class is in namespace $class -> Namespace\className (hopefully folders mirror Namespace)
$class = str_replace("\\", DIRECTORY_SEPARATOR, $class); # avoid linux path separator issues
$fileName = sprintf("%s\\path\\%s.php", __DIR__, $class);
# or
$filename = sprintf("%s\\%s.php", __DIR__, $class); # if class is in namespaace
$filename = sprintf("%s\\%s.php", __DIR__, $class); # if class is in namespace
if (file_exists($fileName)) {
include $fileName;
@ -41,7 +41,7 @@ require "autoload.php";
### Multiple Autoloading
It's possible to resister multiple autoloading functions by calling `spl_autoloaad_register()` multiple times.
It's possible to resister multiple autoloading functions by calling `spl_autoload_register()` multiple times.
```php
# prepend adds the function at the start of the queue

View file

@ -23,7 +23,7 @@ try {
### Queries
To execute a query it's necessaty to "prepare it" with *parameters*.
To execute a query it's necessary to "prepare it" with *parameters*.
```php
# literal string with markers
@ -34,9 +34,9 @@ WHERE field <operator> :marker'
$stmt = $pdo->prepare($sql, $options_array); # returns PDOStatement, used to execute the query
$stmt->execute([ ':marker' => value ]); # substitute marker with actual value
# fetchAll returns all mathces
$result = $stmt->fetchAll(); # result as associtive array AND numeric array (PDO::FETCH_BOTH)
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); # result as associtive array
# fetchAll returns all matches
$result = $stmt->fetchAll(); # result as associative array AND numeric array (PDO::FETCH_BOTH)
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); # result as associative array
$result = $stmt->fetchAll(PDO::FETCH_NUM); # result as array
$result = $stmt->fetchAll(PDO::FETCH_OBJ); # result as object of stdClass
$result = $stmt->fetchAll(PDO::FETCH_CLASS, ClassName::class); # result as object of a specific class
@ -90,13 +90,13 @@ $stmt->debugDumpParams(); # print the SQL query that has been sent to the datab
```php
$db = SQLite3("db_file.sqlite3"); // connection
$stmt = $db->prepare("SELECT fields FROM tables WHERE field <operator> :marker"); // preapre query
$stmt = $db->prepare("SELECT fields FROM tables WHERE field <operator> :marker"); // prepare query
$stmt->bindParam(":marker", $variable); // param binding
$result = $stmt->execute(); // retireve records
$result = $stmt->execute(); // retrieve records
$result->finalize(); // close result set, recommended calling before another execute()
$records = $results->fetchArray(SQLITE3_ASSOC); // extract records as array (flase if no results)
$records = $results->fetchArray(SQLITE3_ASSOC); // extract records as array (false if no results)
```
**NOTE**: Result set objects retrieved by calling `SQLite3Stmt::execute()` on the same statement object are not independent, but rather share the same underlying structure. Therefore it is recommended to call `SQLite3Result::finalize()`, before calling `SQLite3Stmt::execute()` on the same statement object again.

View file

@ -14,13 +14,13 @@ class Foo
## Dependency Injection Container
The **Dependecy Injection Container** (DIC) allow to archive all the dependencies in a single `Container` class. Some offer automatic resolution of the dependecies.
The **Dependency Injection Container** (DIC) allow to archive all the dependencies in a single `Container` class. Some offer automatic resolution of the dependencies.
## [PHP-DI](https://php-di.org/)
The dependency injection container for humans. Installation: `composer require php-di/php-di`
- **Autowire** functionality: the ability of the container to create and inject the dependecy automatically.
- **Autowire** functionality: the ability of the container to create and inject the dependency automatically.
- Use of [Reflection](https://www.php.net/manual/en/intro.reflection.php)
- Configuration of the container through annotations & PHP code.
@ -57,7 +57,7 @@ class Foo
// config.php
use Psr\Container\ContainerInterface;
// config "primitrive" dependencies (dependecy => construct & return)
// config "primitive" dependencies (dependency => construct & return)
return [
'dsn' => 'sqlite:db.sq3',
PDO::class => function(ContainerInterface $c) {

View file

@ -26,7 +26,7 @@ In `config.php`:
```php
//config.php
//store configuration options in associtive array
//store configuration options in associative array
return [
setting => value,
setting = value,
@ -34,7 +34,7 @@ return [
```
```php
$config = include "config.php"; // retireve config and store into variable
$config = include "config.php"; // retrieve config and store into variable
```
## Namespace
@ -42,7 +42,7 @@ $config = include "config.php"; // retireve config and store into variable
[PSR-4 Spec](https://www.php-fig.org/psr/psr-4/)
```php
namespace Foo\Bar\Baz; # set nemespace for all file contents, \ for nested namespaces
namespace Foo\Bar\Baz; # set namespace for all file contents, \ for nested namespaces
use <PHP_Class> # using a namespace hides standard php classes (WHY?!?)
@ -54,7 +54,7 @@ namespace Foo\Bar\Baz {
};
Foo\Bar\Baz\func(); # use function from Foo\Bar\Baz withous USE instruction
Foo\Bar\Baz\func(); # use function from Foo\Bar\Baz without USE instruction
use Foo\Bar\Baz\func; # import namespace
func(); # use function from Foo\Bar\Baz
@ -106,7 +106,7 @@ if (!function_exists('readline')) {
## Variables
```php
$varibleName = value; # weakly typed
$variableName = value; # weakly typed
echo gettype(&variable); # output type of variable
var_dump($var); # prints info of variable (bit dimension, type & value)
@ -159,7 +159,7 @@ $c = 7E-10; // 0.0000000007
## Strings
A string is a sequrnce of ASCII characters. In PHP a string is an array of charachters.
A string is a sequence of ASCII characters. In PHP a string is an array of characters.
### String Concatenation
@ -172,10 +172,10 @@ $string1 .= $string2; # method 2
```php
strlen($string); # returns the string length
strpos($string, 'substring'); # position of dubstring in string
substr($string, start, len); # ectract substring of len from position start
strtoupper($string); # transfrorm to uppercase
strtolower($string); # transform to lowerchase
strpos($string, 'substring'); # position of substring in string
substr($string, start, len); # extract substring of len from position start
strtoupper($string); # transform to uppercase
strtolower($string); # transform to lowercase
explode(delimiter, string); # return array of substrings
@ -205,8 +205,8 @@ Heterogeneous sequence of values.
$array = (sequence_of_items); # array declaration and valorization
$array = [sequence_of_items]; # array declaration and valorization
# index < 0 selecst items starting from the last
$array[index]; # accest to the items
# index < 0 selects items starting from the last
$array[index]; # access to the items
$array[index] = value; # array valorization (can add items)
$array[] = value; # value appending
@ -279,7 +279,7 @@ $italianDay["Mon"]; # evaluates to Lunedì
## Conditional Instructions
### Conditional Opeartors
### Conditional Operators
| Operator | Operation |
| ----------- | ------------------------ |
@ -299,13 +299,13 @@ With `==` a string evaluates to `0`.
### Logical Operators
| Operator | Example | Result |
| -------- | ----------- | ---------------------------------------------------- | --- | ------------------------------------ |
| -------- | ----------- | ---------------------------------------------------- |
| `and` | `$a and $b` | TRUE if both `$a` and `$b` are TRUE. |
| `or` | `$a or $b` | TRUE if either `$a` or `$b` is TRUE. |
| `xor` | `$a xor $b` | TRUE if either `$a` or `$b` is TRUE, but _not both_. |
| `not` | `!$a` | TRUE if `$a` is _not_ TRUE. |
| `and` | `$a && $b` | TRUE if both `$a` and `$b` are TRUE. |
| `or` | `$a | | $b` | TRUE if either `$a` or `$b` is TRUE. |
| `or` | `$a || $b` | TRUE if either `$a` or `$b` is TRUE. |
### Ternary Operator
@ -317,7 +317,7 @@ condition ?: result_if_false;
### NULL Coalesce
```php
$var1 = $var2 ?? value; # if variable == NULL assign value, othervise return value of $var2
$var1 = $var2 ?? value; # if variable == NULL assign value, otherwise return value of $var2
# equivalent to
$var1 = isset($var2) ? $var2 : value
@ -328,7 +328,7 @@ $var1 = isset($var2) ? $var2 : value
```php
$a <=> $b;
# equivalen to
# equivalent to
if $a > $b
return 1;
if $a == $b
@ -445,7 +445,7 @@ do {
[Function Docstring](https://make.wordpress.org/core/handbook/best-practices/inline-documentation-standards/php/)
Parameters with default values are optional in the function call and must be the last ones in the function declaration. Return type is optional if type checking is diasbled.
Parameters with default values are optional in the function call and must be the last ones in the function declaration. Return type is optional if type checking is disabled.
```php
declare(strict_types=1); # activates type checking
@ -516,7 +516,7 @@ function functionName (?type $parameter): ?Type
## Anonymous Functions (Closure)
```php
# declaration and assignement to variable
# declaration and assignment to variable
$var = function (type $parameter) {
# code here
};
@ -576,12 +576,12 @@ class ClassName
const CONSTANT = value; # public by default
public $attribute; # null by default if not assigned
public Type $attribute; # specifing the type is optional, it will be enforced if present
public Type $attribute; # specifying the type is optional, it will be enforced if present
# class constructor
public function __construct(value)
{
$this->attrivute = value
$this->attribute = value
}
public getAttribute(): Type
@ -650,7 +650,7 @@ class ClassName
### Inheritance
If a class is defind `final` it can't be extended.
If a class is defined `final` it can't be extended.
If a function is declared `final` it can't be overridden.
```php
@ -664,7 +664,7 @@ class Child extends Parent
### Abstract Class
Abstract calsses cannot be instantiated;
Abstract classes cannot be instantiated;
```php
abstract class ClassName
@ -701,7 +701,7 @@ class ClassName implements InterfaceName {
`Traits` allows the reutilization of code inside different classes without links of inheritance.
It can be used to mitigate the problem of _multiple inheritance_, which is absent in PHP.
In case of functions name conflic it's possible to use `insteadof` to specify which function to use. It's also possible to use an _alias_ to resolve the conflicts.
In case of functions name conflict it's possible to use `insteadof` to specify which function to use. It's also possible to use an _alias_ to resolve the conflicts.
```php
trait TraitName {
@ -729,7 +729,7 @@ $obj->method(new class implements Interface {
## Serialization & JSON
```php
$serialized = serialize($obj); # serailization
$serialized = serialize($obj); # serialization
$obj = unserialize($serialized); # de-serialization
$var = json_decode(string $json, bool $associative); # Takes a JSON encoded string and converts it into a PHP variable.ù
@ -752,7 +752,7 @@ file_get_contents(filename); // read whole file
```php
preg_match('/PATTERN/', string $subject, array $matches); # returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred
# $mathces[0] = whole matched string
# $matches[0] = whole matched string
# $matches[i] = i-th group of the regex
```
@ -805,7 +805,7 @@ Algorithms currently supported:
- **threads** (integer) - Number of threads to use for computing the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_THREADS.
```php
password_hash($passwrd, $algorithm); # create a new password hash using a strong one-way hashing algorithm.
password_hash($password, $algorithm); # create a new password hash using a strong one-way hashing algorithm.
password_verify($password, $hash); # Verifies that a password matches a hash
```
@ -814,7 +814,7 @@ password_verify($password, $hash); # Verifies that a password matches a hash
Types of PHP errors:
- **Fatal Error**: stop the execution of the program.
- **Warning**: generataed at runtime, does not stop the execution (non-blocking).
- **Warning**: generated at runtime, does not stop the execution (non-blocking).
- **Notice**: informative errors or messages, non-blocking.
```php
@ -849,7 +849,7 @@ ini_set("error_log", "path\\error.log"); // set log file
```php
// generate E_USER_ errors
trigger_error("message"); // defaul type: E_USER_NOTICE
trigger_error("message"); // default type: E_USER_NOTICE
trigger_error("message", E_USER_<Type>);
trigger_error("Deprecated Function", E_USER_DEPRECATED);
@ -873,9 +873,9 @@ PHP offers the possibility to handle errors with the _exception model_.
```php
try {
// dangerous code
} catch(ExcpetionType1 | ExceptionType2 $e) {
} catch(ExceptionType1 | ExceptionType2 $e) {
printf("Errore: %s", $e->getMessage());
} catch(Excpetion $e) {
} catch(Exception $e) {
// handle or report exception
}

View file

@ -2,7 +2,7 @@
## [PSR-7](https://www.php-fig.org/psr/psr-7/)
Standard of the PHP Framework Interop Group that defines common interafces for handling HTTP messages.
Standard of the PHP Framework Interop Group that defines common interfaces for handling HTTP messages.
- `Psr\Http\Message\MessageInterface`
- `Psr\Http\Message\RequestInterface`

View file

@ -23,7 +23,7 @@ composer create-project ezimuel/simple-mvc
| |- route.php --> routing
|- public
| |- img
| |- index.php --> app entrypoint
| |- index.php --> app entry-point
|- src
| |- Model
| |- View --> Plates views
@ -33,7 +33,7 @@ composer create-project ezimuel/simple-mvc
| |- Controller
```
### `indedx.php`
### `index.php`
```php
<?php

View file

@ -4,7 +4,7 @@
To separate HTML code and PHP code it's possible to use **templates** with markers for variable substitution.
Variables are created in the PHP code and are passed to the template in the **rendering** phase.
The server transmitts only the `index.php` file to the user. The php file renders the templates as needed.
The server transmits only the `index.php` file to the user. The php file renders the templates as needed.
```html
<html>
@ -20,7 +20,7 @@ The server transmitts only the `index.php` file to the user. The php file render
## [Plates](https://platesphp.com/)
Plates is a templete engine for PHP. A templete engine permits to separate the PHP code (businnes logic) from the HTML pages.
Plates is a template engine for PHP. A template engine permits to separate the PHP code (business logic) from the HTML pages.
Installation through composer: `composer require league/plates`.
@ -51,14 +51,14 @@ echo $templates->render("template_name", [
</html>
```
Variables in the template are created through an associtve array `key => value`. The key (`"key"`) becomes a variable (`$key`) in the template.
Variables in the template are created through an associative array `key => value`. The key (`"key"`) becomes a variable (`$key`) in the template.
### Layout
It's possible to create a layout (a model) for a group of pages to make that identical save for the contents.
In a layout it's possible to create a section called **content** that identifies content that can be specified at runtime.
**NOTE**: Sinsce only the template has the data passed eventual loops have to be done there.
**NOTE**: Since only the template has the data passed eventual loops have to be done there.
```php
# index.php
@ -94,7 +94,7 @@ echo $template->render('template_name', [ "marker" => value, ... ]);
It's necessary to verify that the output is in the necessary format.
Plates offerts `$this->escape()` or `$this->e()` to validate the output.
Plates offers `$this->escape()` or `$this->e()` to validate the output.
In general the output validation allows to prevent [Cross-Site Scripting][owasp-xss] (XSS).
[owasp-xss]: https://owasp.org/www-community/attacks/xss/

View file

@ -43,7 +43,7 @@ PHPUnit can be configured in a XML file called `phpunit.xml`:
### Test Structure
**PHPUnit** tests are grouped in classes suffixed with `Test`. Each class *extends* `PHPUnit\Framework\TestCase`.
A test is a method of a *test class* prefized with `test`.
A test is a method of a *test class* prefixed with `test`.
PHPUnit is executed from the command line with `vendor/bin/phpunit --colors`.
```php
@ -85,10 +85,10 @@ class FilterTest extends TestCase
- `assertFalse()`: verifies that the element is false
- `assertEmpty()`: verifies that the element is empty
- `assertEquals()`: verifies that the two elements are equal
- `assertGreaterThan()`: verifies that the element is greter than ...
- `assertGreaterThan()`: verifies that the element is greater than ...
- `assertContains()`: verifies that the element is contained in an array
- `assertInstanceOf()`: verifies that the element is an instance of a specific class
- `assertArrayHasKey(mixed $key, array $array)`: verify taht a sopecific key is in the array
- `assertArrayHasKey(mixed $key, array $array)`: verify that a specific key is in the array
### [PHPUnit Testing Exceptions](https://phpunit.readthedocs.io/en/9.3/writing-tests-for-phpunit.html#testing-exceptions)
@ -98,13 +98,13 @@ public function testAggiungiEsameException(string $esame)
$this->expectException(Exception::class);
$this->expectExceptionMessage("exception_message");
// execute code that sould throw an exception
// execute code that should throw an exception
}
// https://github.com/sebastianbergmann/phpunit/issues/2484#issuecomment-648822531
public function testExceptionNotTrown()
public function testExceptionNotThrown()
{
$exceptioWasTrown = false;
$exceptionWasThrown = false;
try
{
@ -112,10 +112,10 @@ public function testExceptionNotTrown()
}
catch (EsameException $e)
{
$exceptioWasTrown = true;
$exceptionWasThrown = true;
}
$this->assertFalse($exceptioWasTrown);
$this->assertFalse($exceptionWasThrown);
}
// same as
@ -168,7 +168,7 @@ class DataTest extends TestCase
$this->assertEquals($expected, $a + $b);
}
// test recieves array contents as input
// test receives array contents as input
public function provider()
{
// must return array of arrays
@ -178,7 +178,7 @@ class DataTest extends TestCase
];
}
// test recieves array of arrays as input
// test receives array of arrays as input
public function provideArrayOfArrays()
{
return [
@ -226,5 +226,5 @@ class UnitTest extends TestCase
### Code Coverage (needs [XDebug](https://xdebug.org/))
```ps1
vendor/bin/phpunit --coverage-text # code cverage analisys in the terminal
vendor/bin/phpunit --coverage-text # code coverage analysis in the terminal
```

View file

@ -12,7 +12,7 @@ PHP -S <ip:post> file.php # redirect requests to single file
## HTTP Methods
Handling of HTTP requests happend using the following global variables:
Handling of HTTP requests happens using the following global variables:
- `$_SERVER`: info on request headers, version, URL path and method (dict)
- `$_GET`: parameters of get request (dict)
@ -54,7 +54,7 @@ if (! move_uploaded_file($_FILES['photo']['tmp_name'], $path)) {
exit();
}
echo'<h1>File succesfully sent</h1>';
echo'<h1>File successfully sent</h1>';
```
### `$_SERVER`
@ -80,8 +80,8 @@ $_SERVER["HTTP_USER_AGENT"];
All sites **must** have a page for the consensus about using cookies.
**Cookies** are HTTP headers used to memorize key-value info *on the client*. They are sent from the server to the client to keep track of info on the user that is visting the website.
When a client recieves a HTTP response that contains `Set-Cookie` headers it has to memorize that info and reuse them in future requests.
**Cookies** are HTTP headers used to memorize key-value info *on the client*. They are sent from the server to the client to keep track of info on the user that is visiting the website.
When a client receives a HTTP response that contains `Set-Cookie` headers it has to memorize that info and reuse them in future requests.
```http
Set-Cookie: <cookie-name>=<cookie-value>
@ -95,7 +95,7 @@ Set-Cookie: <cookie-name>=<cookie-value>; HttpOnly
Anyone can modify the contents of a cookie; for this reason cookies **must not contain** *personal or sensible info*.
When a clien has memorized a cookie, it is sent in successive HTTP requests through the `Cookie` header.
When a client has memorized a cookie, it is sent in successive HTTP requests through the `Cookie` header.
```http
Cookie: <cookie-name>=<cookie-value>
@ -114,7 +114,7 @@ string $name,
[ bool $httponly = false ] // accessible only through http (no js, ...)
)
// examle: memorize user-id 112 with 24h expiry for site example.com
// example: memorize user-id 112 with 24h expiry for site example.com
setcookie ("User-id", "112", time() + 3600*24, "/", "example.com");
// check if a cookie exists
@ -123,12 +123,12 @@ if(isset($_COOKIE["cookie_name"])) {}
### [$_SESSION](https://www.php.net/manual/en/ref.session.php)
**Sessions** are info memorized *on the server* assoiciated to the client that makes an HTTP request.
**Sessions** are info memorized *on the server* associated to the client that makes an HTTP request.
PHP generates a cookie named `PHPSESSID` containing a *session identifier* and an *hash* generated from `IP + timestamp + pseudo-random number`.
To use the session it's necesary to recall the function `session_start()` at the beginning of a PHP script that deals with sessions.
After starting the session information in be savend in the `$_SESSION` array.
To use the session it's necessary to recall the function `session_start()` at the beginning of a PHP script that deals with sessions.
After starting the session information in be saved in the `$_SESSION` array.
```php
$_SESSION["key"] = value; // save data in session file (serialized data)