PHP Best Practices and Living Standards Martin Kruli

  • Slides: 28
Download presentation
PHP Best Practices and Living Standards Martin Kruliš by Martin Kruliš (v 1. 1)

PHP Best Practices and Living Standards Martin Kruliš by Martin Kruliš (v 1. 1) 28. 3. 2018 1

Coding Style only opening tag (no closing) <? php namespace VendorPackage; namespace on first

Coding Style only opening tag (no closing) $b) { new block opening on the same line $foo->bar($a, $b); } } } 4 space indenting by Martin Kruliš (v 1. 1) 28. 3. 2018 2

Standardization PSR � PHP Standard Recommendations ◦ Standardization beyond language specifications ◦ Improves cooperation,

Standardization PSR � PHP Standard Recommendations ◦ Standardization beyond language specifications ◦ Improves cooperation, library designs, … ◦ Accepted �PSR-1, PSR-2 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 1. 1) 28. 3. 2018 3

Autoloading � Automatic Loading of Classes ◦ Useful for libraries, reduces the number of

Autoloading � Automatic Loading of Classes ◦ Useful for libraries, reduces the number of includes ◦ __autoload(), spl_autoload_register() � PSR-4 Autoloading ◦ Defines naming conventions for the relation namespaces + classes vs directories + files ◦ Example �ExamplesFooBar class �/lib/Examples/Foo/Bar. php file by Martin Kruliš (v 1. 1) 28. 3. 2018 4

Components � Component-based Development ◦ Modern applications use components to promote encapsulation and separation

Components � Component-based Development ◦ Modern applications use components to promote encapsulation and separation of concerns �Component – a software module that provides some well defined functionality through a set of interfaces �In PHP, typically a class (or small set of classes) that implements well-defined interface(s) ◦ Component construction and management �A centralized manager (application server, container, …) has to be present to create components �Especially to handle component dependencies by Martin Kruliš (v 1. 1) 28. 3. 2018 5

Components � Example ◦ Components and their dependencies Presenters Page Presenters Template Renderer Logger

Components � Example ◦ Components and their dependencies Presenters Page Presenters Template Renderer Logger Mailer User Auth. Database (ORM, Not. ORM) by Martin Kruliš (v 1. 1) 28. 3. 2018 6

Containers � Component Management ◦ Creation and interlinking may be tedious �Who creates components?

Containers � Component Management ◦ Creation and interlinking may be tedious �Who creates components? �When are the components created? �Where is the component configuration? �How do one component find other components it needs to use? �… ◦ Better to be managed centrally �Using application server, container, component registry, … by Martin Kruliš (v 1. 1) 28. 3. 2018 7

Dependency Injection � Dependency Injection ◦ Design pattern that implements inversion of control �Component

Dependency Injection � Dependency Injection ◦ Design pattern that implements inversion of control �Component is not responsible for seeking its own dependencies �Dependencies are injected externally (by the container) ◦ Declaring dependencies �In configuration, by annotations, using reflection, … �Problem of cyclic dependencies �DB component requires log to log errors �Log may require DB component to save messages by Martin Kruliš (v 1. 1) 28. 3. 2018 8

Dependency Injection � Example Component naming convention /** * @component Welcome. Page */ class

Dependency Injection � Example Component naming convention /** * @component Welcome. Page */ class Welcome. Page. Controller implements IController { Annotations (inject by interface) /** @inject IDatabase */ public $db; /** @inject name="News. Service" */ public $news; Annotations (inject by name) function __construct(ILog $log) {. . . } } Constructor injection (by type hinting) by Martin Kruliš (v 1. 1) 28. 3. 2018 9

Front Controller Revision � Front Controller ◦ Software design pattern that provides centralized entry

Front Controller Revision � Front Controller ◦ Software design pattern that provides centralized entry point for all request (commands) Class/Component Initializing the libraries, setting up components HTTP Front Controller (index. php) Method Action … Controller/Presenter … dispatching Routing and Action Controller/Presenter by Martin Kruliš (v 1. 1) 28. 3. 2018 10

HTTP Request Processing � Request Data Validation ◦ Repetitive, tedious, and error prone ◦

HTTP Request Processing � Request Data Validation ◦ Repetitive, tedious, and error prone ◦ Can be done automatically in a framework class Galery. Presneter extends Presenter { Get PK from $_GET["galery"] and use /** @GET(DBGallery) */ it to find and create DBGallery object public $galery; /** @GET(int) @optional */ Fills in (int)$_GET["offset"] if exists public $offset; /** @param(img) FILES(type="image/jpeg") */ public function Add. Photo. Action($img) {. . . } } $img holds metadata of uploaded file, which has image/jpeg MIME by Martin Kruliš (v 1. 1) 28. 3. 2018 11

HTTP Request Processing � PHP HTTP Wrapper ◦ Automatically loads data into global fields

HTTP Request Processing � PHP HTTP Wrapper ◦ Automatically loads data into global fields �$_GET, $_POST, $_FILES, $_SERVER (headers), … � Problems ◦ Tied strictly to URL query encoding �SEO applications may require different URL format ◦ Only one request may be processed by the script �Modern applications may be more complex ◦ Global variables go against dependency injection ◦ Tedious testing �It is more difficult to perform unit tests by Martin Kruliš (v 1. 1) 28. 3. 2018 12

PSR HTTP API � PSR-7 HTTP Message Interface ◦ Defines two interfaces �PsrHttpMessageRequest. Interface

PSR HTTP API � PSR-7 HTTP Message Interface ◦ Defines two interfaces �PsrHttpMessageRequest. Interface �PsrHttpMessageResponse. Interface �derived from PsrHttpMessage. Interface ◦ These interfaces encapsulate both headers and body of request/response �Provide easy access/manipulation with headers �Streaming interface for body �Better upload handling (Uploaded. File. Interface) by Martin Kruliš (v 1. 1) 28. 3. 2018 13

REST API � Representational State Transfer (REST) ◦ Server API which offers retrieval and

REST API � Representational State Transfer (REST) ◦ Server API which offers retrieval and manipulation with application resources in a HTTP-compliant way �Resources are identified by URIs �Operations are performed by HTTP requests ◦ REST formal constraints are �Client-server model �Stateless interface (no client context is cached at server) �Cacheable (response defines whether it can be cached) �Uniform interface �Layered system (proxies, servers may be replicated) by Martin Kruliš (v 1. 1) 28. 3. 2018 14

REST API � Representational State Transfer (REST) ◦ HTTP request methods reflect desired operations

REST API � Representational State Transfer (REST) ◦ HTTP request methods reflect desired operations �GET – retrieve the resource (nullipotent) �POST – append new sub-entity in the resource �PUT – insert/replace the resource (idempotent) �DELETE – remove the resource (idempotent) ◦ Example �API for photo gallery �/gallery – collection of all galleries �/gallery/kittens - photos in gallery with ID=kittens �/gallery/kittens/kitten 01 – photo kitten 01 by Martin Kruliš (v 1. 1) 28. 3. 2018 15

REST API � REST Example /gallery (collection of galleries) /gallery/kittens (photos in gallery) …/kitten

REST API � REST Example /gallery (collection of galleries) /gallery/kittens (photos in gallery) …/kitten 01 (single photo) Get the list of all galleries (JSON) Get the list of photos in the gallery (JSON) Get the image (jpeg) POST Create a new gallery Create a new photo in a gallery Not generally used. Perhaps for adding image metadata… PUT Replace list of galleries (atypical) Replace entire list of photos in gallery Replace/insert an image (of given ID) DELETE Empty the whole application Remove all photos of a gallery Remove the given image GET by Martin Kruliš (v 1. 1) 28. 3. 2018 16

PHP Micro Frameworks � PHP Slim Framework Example $app = new SlimApp; $app->get('/hello/{name}', function

PHP Micro Frameworks � PHP Slim Framework Example $app = new SlimApp; $app->get('/hello/{name}', function (Request $request, Response $response) { $name = $request->get. Attribute('name'); $response->get. Body()->write("Hello, $name"); return $response; }); $app->run(); by Martin Kruliš (v 1. 1) 28. 3. 2018 17

Open. API � Open. API Specification (Swagger API) ◦ Machine-readable way how to describe

Open. API � Open. API Specification (Swagger API) ◦ Machine-readable way how to describe interfaces of RESTful web services �Model-driven development at interface level ◦ Swagger Tools �Visual editor of Open. API specifications �Code generator (generate stubs in various languages) �Documentation generator/browser �Interactive UI in HTML 5 �Testing and validation tools by Martin Kruliš (v 1. 1) 28. 3. 2018 18

Error Handling � Application Errors Who is General Failure and why is he reading

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 1. 1) 28. 3. 2018 19

Errors in PHP � Error Levels ◦ Define the severity of the error �E_ERROR

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 1. 1) 28. 3. 2018 20

Error Handling in PHP � Error Control (Silence) Operator ◦ Symbol @ prepended to

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 1. 1) 28. 3. 2018 21

Exceptions � Concept of Exceptions ◦ Similar to other object languages �Exceptions are thrown

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 1. 1) 28. 3. 2018 22

Exceptions � Try-catch Blocks ◦ Exception-safe code is wrapped in try block ◦ First

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 1. 1) 28. 3. 2018 23

Exceptions � Creating Custom Exceptions ◦ Exception class is derived from Exception ◦ Derived

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 1. 1) 28. 3. 2018 24

Logging � Logger ◦ Component that ensures logging ◦ Works as a sink for

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 Example by Martin Kruliš (v 1. 1) 28. 3. 2018 25

Configuration � Application Configuration ◦ Essential for larger projects ◦ Structured format �Easy to

Configuration � Application Configuration ◦ Essential for larger projects ◦ Structured format �Easy to write, easy to access from code ◦ API that provides read-only access to the values �In a structured way (nested arrays/objects) ◦ Typical formats �Native PHP (e. g. , array declaration) �INI, XML, JSON, SQLite, … �Haml, Yaml, Neon, … Example by Martin Kruliš (v 1. 1) 28. 3. 2018 26

Caching � Caching ◦ Universal concept for reducing I/O or computations �Database selects, file

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 1. 1) 28. 3. 2018 27

Discussion by Martin Kruliš (v 1. 1) 28. 3. 2018 28

Discussion by Martin Kruliš (v 1. 1) 28. 3. 2018 28