note 118617 added to language.oop5.magic

From: Date: Sat, 09 Jan 2016 04:30:07 +0000
Subject: note 118617 added to language.oop5.magic
Groups: php.notes 
Request: Send a blank email to php-notes+get-204629@lists.php.net to get a copy of this message
A simple API wrapper, using __call() and the PHP 5.6 "..." token. http://php.net/manual/functions.arguments.php#functions.variable-arg-list <?php namespace Example; use Exception; use ReflectionClass; use SomeApiInterface; use SomeHttpClient; use SomeEndpointHandler; /** * Class SomeApiWrapper * * @method SomeEndpointHandler method1(MethodParams $param1) * @method SomeEndpointHandler method2(MethodParams $param1, AuthParams $param2 = null) * ... * @method SomeEndpointHandler method42() */ class SomeApiWrapper{ /** * @var \SomeHttpClient */ private $httpClient; /** * @var array */ private $methodMap = []; /** * SomeApiWrapper constructor. */ public function __construct(){ $this->mapApiMethods(); $this->httpClient = new SomeHttpClient(); } /** * The API is flat and has ~ 150 endpoints, all of which take optional parameters * from up to 3 groups (method params, authentication, filters). Instead of * implementing the interface and adding countless stubs that have basically * the same signature, i just map its methods here and use __call(). */ private function mapApiMethods(){ $reflectionClass = new ReflectionClass(SomeApiInterface::class); foreach($reflectionClass->getMethods() as $m){ $this->methodMap[] = $m->name; } } /** * Thanks to the PHP 5.6+ "..." token, there's no hassle with the arguments anymore * (ugh, bad pun). Just hand the method parameters into the endpoint handler, * along with other mandatory params - type hints are your friends. * * It's magic! * * @param string $method * @param array $arguments * * @return \SomeEndpointHandler * @throws \Exception */ public function __call($method, $arguments){ if(in_array($method, $this->methodMap)){ return new SomeEndpointHandler($this->httpClient, $method, ...$arguments); } throw new Exception('Endpoint "'.$method.'" does not exist'); } } ---- Server IP: 72.52.91.14 Probable Submitter: 84.162.196.225 ---- Manual Page -- http://php.net/manual/en/language.oop5.magic.php Edit -- https://master.php.net/note/edit/118617 Del: integrated -- https://master.php.net/note/delete/118617/integrated Del: useless -- https://master.php.net/note/delete/118617/useless Del: bad code -- https://master.php.net/note/delete/118617/bad+code Del: spam -- https://master.php.net/note/delete/118617/spam Del: non-english -- https://master.php.net/note/delete/118617/non-english Del: in docs -- https://master.php.net/note/delete/118617/in+docs Del: other reasons-- https://master.php.net/note/delete/118617 Reject -- https://master.php.net/note/reject/118617 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#204629) next »