PHP Standardization and A Few Loose Ends Martin
- Slides: 24
PHP Standardization and A Few Loose Ends Martin Kruliš by Martin Kruliš (v 2. 0) 27. 3. 2020 1
Standard PHP Library � SPL Data Structures ◦ Data structures that should replace array �Spl. Doubly. Linked. List �Spl. Stack �Spl. Queue �Spl. Heap, Spl. Max. Heap, Spl. Min. Heap �Spl. Priority. Queue �Spl. Fixed. Array �Spl. Object. Storage by Martin Kruliš (v 2. 0) 27. 3. 2020 2
Standard PHP Library � SPL ◦ ◦ ◦ Iterators Array. Iterator Directory. Iterator Glob. Iterator Recursive. Directory. Iterator Regex. Iterator � SPL Functions ◦ spl_object_hash() ◦ spl_object_id() Unique object identification (valid as long as object lives) hash ~ string, id ~ int by Martin Kruliš (v 2. 0) 27. 3. 2020 3
Standardization PSR � PHP Standard Recommendations ◦ Standardization beyond language specifications ◦ Improves cooperation, library designs, … ◦ Accepted �PSR-1, PSR-12 Coding style guidelines �PSR-3 Logger interface �PSR-4 Autoloading (classes) �PSR-7 HTTP message interface �… ◦ Drafts, pending reviews �Container interface, PHPDoc standard, … by Martin Kruliš (v 2. 0) 27. 3. 2020 4
Autoloading � Automatic Loading of Classes ◦ Useful for libraries, reduces the number of includes ◦ Global function __autoload() �Called automatically when undeclared class is accessed ◦ spl_autoload_register() �Register (possibly multiple) callback handler(s) function __autoload($class. Name) { if (file_exists("libs/$class. Name. php")) include "libs/$class. Name. php"; else log("Class $class. Name is not defined!"); } by Martin Kruliš (v 2. 0) 27. 3. 2020 5
Autoloading � PSR-4 Autoloading ◦ Defines naming conventions for the relation namespaces + classes vs directories + files �Simplest approach is �Namespaces ~ directories �Classes ~ file names (+. php extension) ◦ Example �ExamplesFooBar class �<projectroot>/lib/Examples/Foo/Bar. php file The convention is slightly more complicated, but you get the general idea… by Martin Kruliš (v 2. 0) 27. 3. 2020 6
Error Handling � Application Errors Who is General Failure and why is he reading my disk? ◦ User errors (e. g. , filling a wrong value to form) �Ideally, they should be part of normal operations (application explains problem/offers remedy) ◦ Temporary errors/soft errors (e. g. , DBMS is offline) �“Try it later” message + notify administrator by e-mail ◦ Hard errors (bugs) �Generic message for the user “error occurred …” �Log the error and notify administrator �Position in the code, stack trace, variable dumps, … �URL, POST body, logged user, session data, … �In some cases it might help to allow user add comments by Martin Kruliš (v 2. 0) 27. 3. 2020 7
Errors in PHP � Error Levels ◦ Define the severity of the error �E_ERROR – fatal errors, terminate the script �E_WARNING – severe errors, but recoverable �E_NOTICE – unusual situations (possible error) �E_USER_xxx – user level error, warning, or notice �E_STRICT – suggestion for improvement ◦ The log can filter selected error levels �Controlled in php. ini or by error_reporting() ◦ User errors can be triggered manually �trigger_error() by Martin Kruliš (v 2. 0) 27. 3. 2020 8
Error Handling in PHP � Error Control (Silence) Operator ◦ Symbol @ prepended to an expression ◦ All error messages from the expression are ignored ◦ For specific local solutions only (use with caution) $data = @file('data_file. txt') or die('Error…'); � Information about Errors ◦ The handling callback gets error level and position ◦ debug_backtrace() – retrieves current call stack ◦ debug_print_backtrace() – prints call stack by Martin Kruliš (v 2. 0) 27. 3. 2020 9
Exceptions � Concept of Exceptions ◦ Similar to other object languages �Exceptions are thrown and caught (throw, catch) �Exception is an object of class Exception or derived class ◦ Used for reporting errors �Especially from deeply nested code ◦ Note that … �Uncaught exception causes Fatal Error �Destructors should not throw exceptions �Throwing-catching process is somewhat slow by Martin Kruliš (v 2. 0) 27. 3. 2020 10
Exceptions � Try-catch Blocks ◦ Exception-safe code is wrapped in try block ◦ First matching catch block handles the exception �Exception is matched by its class try { . . . throw new Exception('Error …'); . . . } catch (My. Exception $e) { . . . My exception handler. . . } catch (Exception $e) { . . . Generic exception handler. . . } by Martin Kruliš (v 2. 0) 27. 3. 2020 11
Exceptions � SPL Exceptions ◦ Logic. Exception �Bad. Function. Call. Exception �Bad. Method. Call. Exception �Domain. Exception �Invalid. Argument. Exception �Lengt. Exception �Out. Of. Range. Exception ◦ Runtime. Exception �Out. Of. Bounds. Exception �Overflow. Exception �Range. Exception �Underflow. Exception �Unexpected. Value. Exception by Martin Kruliš (v 2. 0) 27. 3. 2020 12
Exceptions � Creating Custom Exceptions ◦ Exception class is derived from Exception ◦ Derived classes need not to override any methods �If the constructor is overridden, parent constructor must be invoked �It is recommended to redefine __to. String() ◦ When to customize… �To distinguish a new error type �To additional data to the exception object by Martin Kruliš (v 2. 0) 27. 3. 2020 13
Logging � Logger ◦ Component that ensures logging ◦ Works as a sink for all messages �Single write interface, configurable output �Saves messages in files/database, sends e-mails ◦ Distinguish several levels of severity �errors, warnings, notices, … ◦ Many ways to implement �PSR-3 Logger Interface (http: //www. php-fig. org/psr-3/) by Martin Kruliš (v 2. 0) 27. 3. 2020 14
Caching � Caching ◦ Universal concept for reducing I/O or computations �Database selects, file operations, … �Generating previews, summaries, … ◦ May be an important part of data management APIs �E. g. , inside ORM framework ◦ PSR-6 Caching interface �Generalized interface for caching libraries �Both for in-memory and persistent caches �Items are identified by string keys �Items have TTL/expiration �Support for deferred updates by Martin Kruliš (v 2. 0) 27. 3. 2020 15
PHP Code Generators � Code Generators ◦ Like inverse reflection �Code is constructed in memory and then serialized ◦ Nette PHP generator �High level pieces of code are constructed �Low level pieces (e. g. , method body) is created from a string template ◦ PECL AST package �Exposes interface for PHP AST (very low level) ◦ Usage �Instantiating templates, optimizations by Martin Kruliš (v 2. 0) 27. 3. 2020 16
Coding Style (PSR-12) only opening tag (no closing) <? php namespace VendorPackage; namespace on first row use Foo. Interface; use Bar. Class as Bar; class declaration class Foo extends Bar implements Foo. Interface on one row { final public function sample. Method($a, $b = null) { space between if ($a === $b) { operator and vars class/method bar($a); block on } elseif ($a > $b) { new block opening on the same line $foo->bar($a, $b); } } } 4 space indenting by Martin Kruliš (v 2. 0) 27. 3. 2020 17
Doc Comments � Documentation Comments (PSR-5) ◦ And PSR-19 defines list of tags for annotations /** * Computes foo-ish value of given argument. * @param int|null $x * @return int */ function foo($x) { … } /** @var string|null */ private $bar; by Martin Kruliš (v 2. 0) 27. 3. 2020 18
Linter � Avoiding ◦ Linter Code Errors �Software that analyses source code to point out errors, or suspicious constructions �Very important in case of interpreted languages ◦ PHP Linters �Multiple projects exisits �linter-php, phplint �Typically integrated to IDEs �Like Visual Studio Code by Martin Kruliš (v 2. 0) 27. 3. 2020 19
Debugging � PHP XDebug ◦ A module for PHP interpret �Taps into the execution process �Allows suspending execution (breakpoints, stepping) �Memory inspection ◦ Communicates with IDE/client over socket �Meaning the IDE may be on a different computer by Martin Kruliš (v 2. 0) 27. 3. 2020 20
Unit Testing � Testing ◦ Very important part of software development �Tests should be executed automatically ◦ PHPUnit �Each test case is class that extends Test. Case �Each test is a method �Asserts, exception handlers, mockups ◦ Database mockups �Alice – Fixtures Generator �Data generator for database mockups by Martin Kruliš (v 2. 0) 27. 3. 2020 21
Static Analysis � PHP Static Analysis Tools ◦ Static analysis �Analyze the code without actually executing it �More sophisticated than linter �Tries to find errors �Unreachable parts of code �Invariants that will not hold �Invalid operations that will lead to runtime errors ◦ Tools for PHP �PHPStan, Exacat, Phan, Tuli, … by Martin Kruliš (v 2. 0) 27. 3. 2020 22
Composer � Composer ◦ Dependency manager for PHP �Not directly a “package manager” �Manages dependencies per-project ◦ Installs 3 rd party tools and libraries �Records are stored in composer. json �Resolves dependencies �Keeps track of installed packages and versions $> composer create-project nette/sandbox <projectname> $> composer require vendor/package $> composer update by Martin Kruliš (v 2. 0) 27. 3. 2020 23
Discussion by Martin Kruliš (v 2. 0) 27. 3. 2020 24
- She's lucky she has few problems
- Charles by shirley jackson literary elements
- A few vai few
- Few a few little a little exercise
- Complete the sentences. use the following words
- Www.facebook.com.php
- Php php://input
- Distinguish between standardization and grading
- Kmno4 uses
- Test construction and standardization
- Direct method of standardization
- Emirates authority for standardization and metrology logo
- What is raw score in psychology
- Ibm maximo for oil and gas
- Chapter 23 using recipes answer key
- Standardization in product and service design
- Standardization statistics
- Data standardization process
- Milk standardization formula
- Standardization of outputs
- Standardization in product design
- Global directory issues in distributed database system
- Trillium software system competitors
- Coordination through formal hierarchy relies on
- Satori software support