rfc:protocol_type_hinting

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
rfc:protocol_type_hinting [2013/06/26 15:16] – Update RFC, renaming to Structural Typing ircmaxellrfc:protocol_type_hinting [2017/09/22 13:28] (current) – external edit 127.0.0.1
Line 1: Line 1:
 ====== PHP RFC: Structural Type Hinting ====== ====== PHP RFC: Structural Type Hinting ======
-  * Version: 0.1+  * Version: 0.2
   * Date: 2013-06-25    * Date: 2013-06-25 
   * Author: Anthony Ferrara <ircmaxell@php.net>   * Author: Anthony Ferrara <ircmaxell@php.net>
-  * Status: Draft +  * Status: Withdrawn 
   * First Published at: http://wiki.php.net/rfc/protocol_type_hinting   * First Published at: http://wiki.php.net/rfc/protocol_type_hinting
  
Line 89: Line 89:
 } }
 class StaticLogger { class StaticLogger {
-    public static function log($message);+    public static function log($message) { /* blah */ }
 } }
 class OtherLogger { class OtherLogger {
-    public static function log($message, $bar);+    public static function log($message, $bar) { /* blah */ }
 } }
 Bar::foo(new FileLogger); // Good! Bar::foo(new FileLogger); // Good!
Line 100: Line 100:
 ?> ?>
 </file> </file>
 +
 +===== Use-Cases =====
 +
 +==== Flexible Middleware ====
 +
 +Right now there's a project called [[http://stackphp.com/|Stack]]. The premise is to provide middlewares for Symfony's //HttpKernel//. In practice these middlewares are nothing more than decorators for the //HttpKernel//. Let's show the //HttpKernel// Interface:
 +
 +<file php HttpKernelInterface.php>
 +<?php
 +namespace Symfony\Component\HttpKernel;
 +
 +use Symfony\Component\HttpFoundation\Request;
 +
 +interface HttpKernelInterface
 +{
 +    const MASTER_REQUEST = 1;
 +    const SUB_REQUEST = 2;
 +
 +    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true);
 +}
 +?>
 +</file>
 +
 +Really, there isn't anything Symfony specific there. The only specific part is the //Request// class, which is quite big.
 +
 +So right now, middleware has to be coupled on the //HttpKernel// and as such, on the //Request// class and a whole lot of other parts of Symfony...
 +
 +=== Reducing Coupling ===
 +
 +Let's imagine you're creating a firewall middleware to limit requests to a specific IP (or allow for all except a certain IP). As it stands today, you need a large chunk of Symfony to do so.
 +
 +But with Structure Typing, you can create two new interfaces:
 +
 +<file php RequestGetClientIp.php>
 +<?php
 +interface RequestGetClientIp {
 +    public function getClientIp()
 +?>
 +</file>
 +<file php HttpKernelClientIp.php>
 +<?php
 +interface HttpKernelInterfaceForClientIp
 +{
 +    const MASTER_REQUEST = 1;
 +    const SUB_REQUEST = 2;
 +
 +    public function handle(<RequestGetClientIp> $request, $type = self::MASTER_REQUEST, $catch = true);
 +}
 +?>
 +</file>
 +
 +Now, my middleware becomes:
 +
 +<file php firewall.php>
 +<?php
 +class Firewall implements HttpKernelInterfaceForClientIp {
 +    protected $parent = null;
 +    public function __construct(<HttpKernelInterfaceForClientIp> $parent) {
 +        $this->parent = $parent;
 +    }
 +    public function handle(<RequestGetClientIp> $request, $type = self::MASTER_REQUEST, $catch = true) {
 +        if ($request->getClientIp() === '127.0.0.1') {
 +            return $this->parent->handle($request);
 +        }
 +        throw new Exception('Not Authorized');
 +    }
 +}
 +?>
 +</file>
 +
 +The cool thing is that I'm effectively decoupled from Symfony here. If ZendFramework changed their [[https://github.com/zendframework/zf2/blob/master/library/Zend/Http/Client.php#L792|Http\Client]] to use the same basic API, you could re-use the middleware on both, without needing a cross-project dependency between Symfony and Zend (and thereby loading the interfaces on every request.
 +
 +==== Standards Based Interface Declarations ====
 +
 +Currently, the [[https://github.com/php-fig|PSR-FIG Group]] group is starting to publish interfaces for standardized components. At present, this requires that each project that either provides a "standard implementation" or uses a "standard implementation" must declare a dependency on this third project. 
 +
 +This raises a significant issue, because it causes a triangular dependency which requires some external effort to resolve. This means that you need some sort of tool to resolve that dependency for you, or you both sides copy/paste the implementation into their tree, and must "register an autoloader" for that dependency, and the first one to do so will win. Either way, it's not a straight forward solution.
 +
 +For example, take the [[https://github.com/php-fig/log/blob/master/Psr/Log/LoggerInterface.php|PSR-3 LoggerInterface]]
 +
 +<file php LoggerInterface.php>
 +<?php
 +namespace psr\log;
 +interface LoggerInterface
 +{
 +    public function emergency($message, array $context = array());
 +    public function alert($message, array $context = array());
 +    public function critical($message, array $context = array());
 +    public function error($message, array $context = array());
 +    public function warning($message, array $context = array());
 +    public function notice($message, array $context = array());
 +    public function info($message, array $context = array());
 +    public function debug($message, array $context = array());
 +    public function log($level, $message, array $context = array());
 +}
 +?>
 +</file>
 +
 +
 +=== Reducing Coupling ===
 +
 +Using Structural Typing, we can solve this triangular dependency by only requiring the interface when we need it (at the receiver) as opposed to at the producer:
 +
 +We can also narrow the requirement for an acceptable logger based on our application's needs. So we can redefine:
 +
 +<file php Psr3LogWarningAndError.php>
 +<?php
 +interface Psr3LogWarningAndError {
 +    public function error($message, array $context = array());
 +    public function warning($message, array $context = array());
 +}
 +?>
 +</file>
 +<file php MyCode.php>
 +<?php
 +class MyClass {
 +    protected $logger;
 +    public function __construct(<Psr3LogWarningAndError> $logger) {
 +        $this->logger = $logger;
 +    }
 +    public function doSomething($foo) {
 +        if (!$foo) {
 +            $this->logger->warning("Foo!!!", [$foo]);
 +        }
 +    }
 +}
 +?>
 +</file>
 +
 +So now, our code can depend on the narrower interface that we actually need, while allowing all PSR-3 compatible implementations to pass. But it also will allow us to replace polymorphically the logger with a non-PSR-3 logger (because it doesn't implement other parts of the interface, for example), but fulfills our entire need.
 +
 +The key here is that it inverts the dependency on who gets to define what the needed units of functionality are. It allows the receiving code to define the scope of required functionality instead of the sending code.
 +
 +It also solves the triangular dependency problem since the sender never needs to explicitly require the dependency. That can be left for an off-line check (or a test), reducing the amount of and need for dependency resolving tools for the purpose of common interfaces...
 +
 +==== Trait Typing ====
 +
 +Currently, traits do not allow for specifying of typing information. And this is a good thing (it is by design).
 +
 +However, there are many times where we may wish to infer that the functionality presented by a trait is present in an object. An example would be Zend Framework's [[https://github.com/zendframework/zf2/blob/master/library/Zend/EventManager/ProvidesEvents.php|ProvidesEvents Trait]]. It basically looks like this:
 +
 +<file php ProvidesEvents.php>
 +<?php
 +namespace Zend\EventManager;
 +trait ProvidesEvents {
 +    protected $events;
 +    public function setEventManager(EventManagerInterface $events) { /* snip */ }
 +    public function getEventManager() { /* snip */ }
 +}
 +?>
 +</file>
 +
 +As the current system stands, classes that use the trait need to also implement a separate interface to get the message of the behavior across to the receiver that it supports events.
 +
 +With Structural Type Hinting, we can instead hint against the trait directly, which would require a class with the same public API that the trait provides, //irrespective of if it is actually using the trait or not//.
 +
 +<file php RequiresEvents.php>
 +<?php
 +function triggerEvent(<Zend\EventManager\ProvidesEvents> $target, $eventName) {
 +    $target->getEventManager()->trigger($eventName, $target);
 +}
 +?>
 +</file>
 +
 +If the object uses the trait, it will always resolve. But it also gives other classes which implement the same public API the ability to resolve the trait.
 +
 +==== The Place For Current Interfaces ====
 +
 +Why not just get rid of current interfaces and change their behavior to Structural typing (besides the MASSIVE BC break)?
 +
 +In practice there are two reasons (times) that you would use an interface:
 +
 +1. To provide typing information about a domain object (or a value object). This is where the typing actually means something specific to the application.
 +
 +An example would be a User object in an application. You may want to have a UserInterface which the User class implements, because the interface actually implies that the object *belongs* to the domain. It's providing *type* information about the object.
 +
 +2. To provide functionality information about a object. This where the interface really just describes the functionality of the object.
 +
 +An example would be a service which encodes a password. There's no special typing information needed. The interface simply provides a semantic way of identifying the API of the service. So it's not really providing *type*, but more capability.
 +
 +With this new proposal, Type information would still be implemented via traditional interfaces. But capability information would use Structural Typing.
 +
 +So there is very much a place for both to live side-by-side in the same language.
  
 ===== Backward Incompatible Changes ===== ===== Backward Incompatible Changes =====
Line 194: Line 377:
 When run once (with $times = 1): When run once (with $times = 1):
  
-''Interface in 1.5974044799805E-5 seconds, 1.5974044799805E-5 seconds per run +''Interface in 1.5974044799805E-5 seconds, 1.5974044799805E-5 seconds per run'' 
-Structural in 1.4066696166992E-5 seconds, 1.4066696166992E-5 seconds per run + 
-Native in 6.9141387939453E-6 seconds, 6.9141387939453E-6 seconds per run''+''Structural in 1.4066696166992E-5 seconds, 1.4066696166992E-5 seconds per run'' 
 + 
 +''Native in 6.9141387939453E-6 seconds, 6.9141387939453E-6 seconds per run''
  
 The margin of error for the test is approximately the same difference as between Interface and Structural. This means that the performance for a single run is about constant. The margin of error for the test is approximately the same difference as between Interface and Structural. This means that the performance for a single run is about constant.
Line 204: Line 389:
 When run with $times = 1000000; When run with $times = 1000000;
  
-''Interface in 0.50202393531799 seconds, 5.0202393531799E-7 seconds per run +''Interface in 0.50202393531799 seconds, 5.0202393531799E-7 seconds per run'' 
-Structural in 0.48089909553528 seconds, 4.8089909553528E-7 seconds per run + 
-Native in 0.3850359916687 seconds, 3.850359916687E-7 seconds per run''+''Structural in 0.48089909553528 seconds, 4.8089909553528E-7 seconds per run'' 
 + 
 +''Native in 0.3850359916687 seconds, 3.850359916687E-7 seconds per run''
  
 In this case, the margin of error was less than the difference, meaning that the Structural approach is slightly more performant at runtime than the interface based approach. In this case, the margin of error was less than the difference, meaning that the Structural approach is slightly more performant at runtime than the interface based approach.
Line 233: Line 420:
  
  * 0.1 - Initial Draft  * 0.1 - Initial Draft
 + * 0.2 - Rename to Structural Typing, add benchmark results
rfc/protocol_type_hinting.1372259817.txt.gz · Last modified: 2017/09/22 13:28 (external edit)