SlideShare a Scribd company logo
1 of 32
PHP7 Anonymous Classes
?
PHP7 Anonymous Classes
?
PHP7 Anonymous Classes:
Behind the Mask
?
PHP7 Anonymous Classes
• What is an Anonymous Class?
• A class that is defined “inline”, within user code, at runtime
• Sometimes called “inline” or “nested” classes
• Don’t have the scope of the class where they are created
• Not assigned a class name
PHP7 Anonymous Classes
• What is an Anonymous Class?
• How do I use an Anonymous Class?
PHP7 Anonymous Classes
• How do I use an Anonymous Class?
• No name given to the class (internally assigned by PHP)
• Closing semi-colon (;)
• Constructor arguments passed in class definition
• All objects created by the same anonymous class declaration are instances of
that class (the internal class reference is identical).
$objectInstance = new class( 'arguments'... ) {
// defined properties and methods
};
PHP7 Anonymous Classes
function locationFormatBuilder (array $location = []) {
return new class (...$location) {
const POINT_MASK = '% 3d° % 2d' %5.2f" %s';
public function __construct($latitude, $longitude) {
$this->latitude = $latitude;
$this->longitude = $longitude;
}
protected function point($point, $orientation) {
…
return vsprintf(self::POINT_MASK, [$degrees, $minutes, $seconds, $direction]);
}
public function __toString() {
return vsprintf(
'%s, %s',
[$this->point($this->latitude, ['N','S']), $this->point($this->longitude, ['E','W'])]
);
}
};
}
PHP7 Anonymous Classes
$locations = [
[ 51.5074, -0.1278 ], // London
[ 40.7128, -74.0059 ], // New York
[ -22.9068, -43.1729 ], // Rio de Janeiro
[ -33.9249, 18.4241 ], // Cape Town
[ 19.0760, 72.8777 ], // Mumbai
[ 35.6895, 139.6917 ], // Tokyo
[ -33.8688, 151.2093 ], // Sydney
[ 31.7683, 35.2137 ], // Jerusalem
];
foreach ($locations as $location) {
echo locationFormatBuilder($location), PHP_EOL;
}
51° 30' 26.00" N, 0° 7' 40.00" W
40° 42' 46.00" N, 74° 0' 21.00" W
22° 54' 24.00" S, 43° 10' 22.00" W
33° 55' 29.00" S, 18° 25' 26.00" E
19° 4' 33.00" N, 72° 52' 39.00" E
35° 41' 22.00" N, 139° 41' 30.00" E
33° 52' 7.00" S, 151° 12' 33.00" E
31° 46' 5.00" N, 35° 12' 49.00" E
PHP7 Anonymous Classes
PHP7 Anonymous Classes
• How do I use an Anonymous Class?
• Can “implement” and “extend”
• Can use Traits
$objectInstance = new class( 'arguments'... ) {
// defined properties and methods
};
PHP7 Anonymous Classes
• Anonymous Class Factories
• Builds an Anonymous Class that extends the “UserModel” class with optional
Traits
• Uses “eval()”
$anonymousUserInstance = (new AnonymousClassFactory('UserModel'))
->withConstructorArguments($databaseConnection, $loggingEnabled)
->withTraits('softDelete', 'auditable')
->create();
PHP7 Anonymous Classes
trait softDelete {
protected $softDelete = true;
}
trait auditable {
protected $auditable = true;
}
class UserModel {
protected $dbConnection;
protected $loggingEnabled;
public function __construct($dbConnection, $loggingEnabled = false) {
$this->dbConnection = $dbConnection;
$this->loggingEnabled = $loggingEnabled;
}
}
PHP7 Anonymous Classes
$dbConnection = new PDO('sqlite:example.db');
$loggingEnabled = true;
$className = 'UserModel';
$traits = implode(', ', ['softDelete', 'auditable']);
$classDefinition = <<<ANONYMOUS
new class($dbConnection, $loggingEnabled) extends {$className} {
use {$traits};
};
ANONYMOUS;
$anonymousUserInstance = eval("return $classDefinition;");
PHP7 Anonymous Classes
object(class@anonymous)#2 (4) {
["dbConnection":protected]=>
object(PDO)#1 (0) {
}
["loggingEnabled":protected]=>
bool(true)
["softDelete":protected]=>
bool(true)
["auditable":protected]=>
bool(true)
}
PHP7 Anonymous Classes
• Anonymous Class Factories
• In Search of an Anonymous Class Factory
https://markbakeruk.net/2016/05/03/in-search-of-an-anonymous-class-factory/
• Anonymous Class Factory – The Results are in
https://markbakeruk.net/2016/05/12/anonymous-class-factory-the-results-are-in/
$anonymousUserInstance = (new AnonymousClassFactory('UserModel'))
->withConstructorArguments($databaseConnection, $loggingEnabled)
->withTraits('softDelete', 'auditable')
->create();
PHP7 Anonymous Classes
class UserController {
protected $user;
public function __construct(UserModel $user) {
$this->user = $user;
}
}
$controller = new UserController($anonymousUserInstance);
PHP7 Anonymous Classes
• What is an Anonymous Class?
• How do I use an Anonymous Class?
• What Limitations are there to Anonymous Classes?
PHP7 Anonymous Classes
• What Limitations are there to Anonymous Classes?
• Definition and Instantiation in a Single Step
• Cannot be Serialized
• Effectively Final
• No OpCache Optimisations
• No Documentation (DocBlocks)
• No IDE Hinting
PHP7 Anonymous Classes
• What is an Anonymous Class?
• How do I use an Anonymous Class?
• What Limitations are there to Anonymous Classes?
• Why would I use Anonymous Classes?
PHP7 Anonymous Classes
• Why would I use Anonymous Classes?
• One-off Objects
• Private Classes
• Test Mocking
• On-demand Typed Structures (instead of generic arrays or StdClass)
• Ad-hoc adapters in a loosely coupled architecture
• To bypass Autoloading
PHP7 Anonymous Classes
• Why would I use Anonymous Classes? – Private Classes
class deathwatch {
public static function monitor($object, Closure $callback) {
$keyName = 'monitor' . spl_object_hash($object);
$monitor = new class($callback) {
protected $callback;
public function __construct($callback) {
$this->callback = $callback;
}
public function __destruct() {
$callback = $this->callback;
$callback();
}
};
$object->$keyName = $monitor;
}
}
PHP7 Anonymous Classes
• Why would I use Anonymous Classes? – Private Classes
class character {
protected $name;
public function __construct($name) {
$this->name = $name;
}
}
$characters = [
new character('Ned Stark'),
new character('Olenna Tyrell'),
new character('Tywin Lannister'),
new character('Myrcella Baratheon'),
];
PHP7 Anonymous Classes
• Why would I use Anonymous Classes? – Private Classes
deathwatch::monitor($characters[0], function() {
echo 'Oh noes', PHP_EOL;
});
deathwatch::monitor($characters[1], function() {
echo 'Oh yaes', PHP_EOL;
});
deathwatch::monitor($characters[2], function() {
echo 'Oh no, not again!', PHP_EOL;
});
unset($characters[0], $characters[1]);
echo PHP_EOL, '---===---', PHP_EOL, PHP_EOL;
PHP7 Anonymous Classes
• Why would I use Anonymous Classes? – Private Classes
Oh noes
Oh yaes
---===---
Oh no, not again!
PHP7 Anonymous Classes
• Why would I use Anonymous Classes? – Test Mocking
• https://mfyu.co.uk/post/anonymous-classes-in-php-7-are-fantastic-for-tests
PHP7 Anonymous Classes
• Inner- or Nested-Classes
class SpyMaster {
private $targetObject;
protected $objectMission;
public function __construct($targetObject) {
$this->targetObject = $targetObject;
$this->objectMission = new SpyObjectMission($targetObject);
}
protected function getHandler() {
…
}
public function infiltrate() {
return $this->getHandler();
}
}
PHP7 Anonymous Classes
• Inner- or Nested-Classes
class SpyObjectMission {
public $methods = [];
public $invoker;
public function __construct($targetObject) {
$reflector = new ReflectionObject($targetObject);
$this->invoker = $this->getInvoker($reflector, $targetObject);
}
protected function getInvoker(ReflectionObject $reflector, $targetObject) {
$staticMethods = array_column($reflector->getMethods(ReflectionMethod::IS_STATIC), 'name');
$this->methods = array_diff(
array_column($reflector->getMethods(), 'name'), $staticMethods)
);
$invoker = function($methodName, ...$args) {
return self::$methodName(...$args);
};
return $invoker->bindTo($targetObject, get_class($targetObject));
}
}
PHP7 Anonymous Classes
• Inner- or Nested-Classes
protected function getHandler() {
return new class ($this->objectMission) {
private $objectMission;
public function __construct(SpyObjectMission $objectMission) {
$this->objectMission = $objectMission;
}
public function __call($methodName, $args) {
if (in_array($methodName, $this->objectMission->methods)) {
$invoker = $this->objectMission->invoker;
return $invoker($methodName, ...$args);
}
throw new Exception("Object Method {$methodName} does not exist");
}
};
}
PHP7 Anonymous Classes
• Inner- or Nested-Classes
$test = new classThatWeWantToTest(1, 2, 3);
$spy = (new SpyMaster($test))
->infiltrate();
echo 'SPY FOR TEST #1', PHP_EOL;
echo $spy->privateMethodThatWeWantToTest(), PHP_EOL;
PHP7 Anonymous Classes
• Inner- or Nested-Classes
• Closures, Anonymous Classes and an alternative approach to Test Mocking
(Part 2)
• https://markbakeruk.net/2017/07/30/closures-anonymous-classes-and-an-alternative-
approach-to-test-mocking-part-2/
• Closures, Anonymous Classes and an alternative approach to Test Mocking
(Part 4)
• https://markbakeruk.net/2018/01/23/closures-anonymous-classes-and-an-alternative-
approach-to-test-mocking-part-4/
PHP7 Anonymous Classes
Who am I?
Mark Baker
@Mark_Baker
https://github.com/MarkBaker
http://uk.linkedin.com/pub/mark-baker/b/572/171
http://markbakeruk.net

More Related Content

What's hot

PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5Jason Austin
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 
Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNIKirill Kounik
 
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...Khoa Nguyen
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Fwdays
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3Toni Kolev
 
Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toAlexander Makarov
 
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching PatternDeadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Patternchibochibo
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 

What's hot (20)

PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNI
 
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
Cuối cùng cũng đã chuẩn bị slide xong cho seminar ngày mai. Mai seminar đầu t...
 
Introduction to Swift 2
Introduction to Swift 2Introduction to Swift 2
Introduction to Swift 2
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
Yii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading toYii, frameworks and where PHP is heading to
Yii, frameworks and where PHP is heading to
 
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching PatternDeadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking &amp; Hyper Context Switching Pattern
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 

Similar to Anonymous classes2

Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.pptrani marri
 
PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?Sam Thomas
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHPDavid Stockton
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2Mudasir Syed
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHPDavid Stockton
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpAlena Holligan
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classesKumar
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Damien Seguy
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulDavid Engel
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Damien Seguy
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptx06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptxThắng It
 

Similar to Anonymous classes2 (20)

Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
Only oop
Only oopOnly oop
Only oop
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 
PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?PHP unserialization vulnerabilities: What are we missing?
PHP unserialization vulnerabilities: What are we missing?
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
Closer look at PHP Unserialization by Ashwin Shenoi
Closer look at PHP Unserialization by Ashwin ShenoiCloser look at PHP Unserialization by Ashwin Shenoi
Closer look at PHP Unserialization by Ashwin Shenoi
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
 
Php 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find UsefulPhp 5.4: New Language Features You Will Find Useful
Php 5.4: New Language Features You Will Find Useful
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 
OOPs Concept
OOPs ConceptOOPs Concept
OOPs Concept
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptx06-classes.ppt (copy).pptx
06-classes.ppt (copy).pptx
 

More from Mark Baker

Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to ProductionMark Baker
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to ProductionMark Baker
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to ProductionMark Baker
 
A Brief History of Elephpants
A Brief History of ElephpantsA Brief History of Elephpants
A Brief History of ElephpantsMark Baker
 
Aspects of love slideshare
Aspects of love slideshareAspects of love slideshare
Aspects of love slideshareMark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Mark Baker
 
A Brief History of ElePHPants
A Brief History of ElePHPantsA Brief History of ElePHPants
A Brief History of ElePHPantsMark Baker
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding HorrorsMark Baker
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the UntestableMark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Mark Baker
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding HorrorsMark Baker
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Mark Baker
 
Giving birth to an ElePHPant
Giving birth to an ElePHPantGiving birth to an ElePHPant
Giving birth to an ElePHPantMark Baker
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsMark Baker
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsMark Baker
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015Mark Baker
 
Zephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsMark Baker
 

More from Mark Baker (20)

Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
A Brief History of Elephpants
A Brief History of ElephpantsA Brief History of Elephpants
A Brief History of Elephpants
 
Aspects of love slideshare
Aspects of love slideshareAspects of love slideshare
Aspects of love slideshare
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
A Brief History of ElePHPants
A Brief History of ElePHPantsA Brief History of ElePHPants
A Brief History of ElePHPants
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
Testing the Untestable
Testing the UntestableTesting the Untestable
Testing the Untestable
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?Does the SPL still have any relevance in the Brave New World of PHP7?
Does the SPL still have any relevance in the Brave New World of PHP7?
 
Giving birth to an ElePHPant
Giving birth to an ElePHPantGiving birth to an ElePHPant
Giving birth to an ElePHPant
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015
 
Zephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensionsZephir - A Wind of Change for writing PHP extensions
Zephir - A Wind of Change for writing PHP extensions
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 

Anonymous classes2

  • 4. PHP7 Anonymous Classes • What is an Anonymous Class? • A class that is defined “inline”, within user code, at runtime • Sometimes called “inline” or “nested” classes • Don’t have the scope of the class where they are created • Not assigned a class name
  • 5. PHP7 Anonymous Classes • What is an Anonymous Class? • How do I use an Anonymous Class?
  • 6. PHP7 Anonymous Classes • How do I use an Anonymous Class? • No name given to the class (internally assigned by PHP) • Closing semi-colon (;) • Constructor arguments passed in class definition • All objects created by the same anonymous class declaration are instances of that class (the internal class reference is identical). $objectInstance = new class( 'arguments'... ) { // defined properties and methods };
  • 7. PHP7 Anonymous Classes function locationFormatBuilder (array $location = []) { return new class (...$location) { const POINT_MASK = '% 3d° % 2d' %5.2f" %s'; public function __construct($latitude, $longitude) { $this->latitude = $latitude; $this->longitude = $longitude; } protected function point($point, $orientation) { … return vsprintf(self::POINT_MASK, [$degrees, $minutes, $seconds, $direction]); } public function __toString() { return vsprintf( '%s, %s', [$this->point($this->latitude, ['N','S']), $this->point($this->longitude, ['E','W'])] ); } }; }
  • 8. PHP7 Anonymous Classes $locations = [ [ 51.5074, -0.1278 ], // London [ 40.7128, -74.0059 ], // New York [ -22.9068, -43.1729 ], // Rio de Janeiro [ -33.9249, 18.4241 ], // Cape Town [ 19.0760, 72.8777 ], // Mumbai [ 35.6895, 139.6917 ], // Tokyo [ -33.8688, 151.2093 ], // Sydney [ 31.7683, 35.2137 ], // Jerusalem ]; foreach ($locations as $location) { echo locationFormatBuilder($location), PHP_EOL; }
  • 9. 51° 30' 26.00" N, 0° 7' 40.00" W 40° 42' 46.00" N, 74° 0' 21.00" W 22° 54' 24.00" S, 43° 10' 22.00" W 33° 55' 29.00" S, 18° 25' 26.00" E 19° 4' 33.00" N, 72° 52' 39.00" E 35° 41' 22.00" N, 139° 41' 30.00" E 33° 52' 7.00" S, 151° 12' 33.00" E 31° 46' 5.00" N, 35° 12' 49.00" E PHP7 Anonymous Classes
  • 10. PHP7 Anonymous Classes • How do I use an Anonymous Class? • Can “implement” and “extend” • Can use Traits $objectInstance = new class( 'arguments'... ) { // defined properties and methods };
  • 11. PHP7 Anonymous Classes • Anonymous Class Factories • Builds an Anonymous Class that extends the “UserModel” class with optional Traits • Uses “eval()” $anonymousUserInstance = (new AnonymousClassFactory('UserModel')) ->withConstructorArguments($databaseConnection, $loggingEnabled) ->withTraits('softDelete', 'auditable') ->create();
  • 12. PHP7 Anonymous Classes trait softDelete { protected $softDelete = true; } trait auditable { protected $auditable = true; } class UserModel { protected $dbConnection; protected $loggingEnabled; public function __construct($dbConnection, $loggingEnabled = false) { $this->dbConnection = $dbConnection; $this->loggingEnabled = $loggingEnabled; } }
  • 13. PHP7 Anonymous Classes $dbConnection = new PDO('sqlite:example.db'); $loggingEnabled = true; $className = 'UserModel'; $traits = implode(', ', ['softDelete', 'auditable']); $classDefinition = <<<ANONYMOUS new class($dbConnection, $loggingEnabled) extends {$className} { use {$traits}; }; ANONYMOUS; $anonymousUserInstance = eval("return $classDefinition;");
  • 14. PHP7 Anonymous Classes object(class@anonymous)#2 (4) { ["dbConnection":protected]=> object(PDO)#1 (0) { } ["loggingEnabled":protected]=> bool(true) ["softDelete":protected]=> bool(true) ["auditable":protected]=> bool(true) }
  • 15. PHP7 Anonymous Classes • Anonymous Class Factories • In Search of an Anonymous Class Factory https://markbakeruk.net/2016/05/03/in-search-of-an-anonymous-class-factory/ • Anonymous Class Factory – The Results are in https://markbakeruk.net/2016/05/12/anonymous-class-factory-the-results-are-in/ $anonymousUserInstance = (new AnonymousClassFactory('UserModel')) ->withConstructorArguments($databaseConnection, $loggingEnabled) ->withTraits('softDelete', 'auditable') ->create();
  • 16. PHP7 Anonymous Classes class UserController { protected $user; public function __construct(UserModel $user) { $this->user = $user; } } $controller = new UserController($anonymousUserInstance);
  • 17. PHP7 Anonymous Classes • What is an Anonymous Class? • How do I use an Anonymous Class? • What Limitations are there to Anonymous Classes?
  • 18. PHP7 Anonymous Classes • What Limitations are there to Anonymous Classes? • Definition and Instantiation in a Single Step • Cannot be Serialized • Effectively Final • No OpCache Optimisations • No Documentation (DocBlocks) • No IDE Hinting
  • 19. PHP7 Anonymous Classes • What is an Anonymous Class? • How do I use an Anonymous Class? • What Limitations are there to Anonymous Classes? • Why would I use Anonymous Classes?
  • 20. PHP7 Anonymous Classes • Why would I use Anonymous Classes? • One-off Objects • Private Classes • Test Mocking • On-demand Typed Structures (instead of generic arrays or StdClass) • Ad-hoc adapters in a loosely coupled architecture • To bypass Autoloading
  • 21. PHP7 Anonymous Classes • Why would I use Anonymous Classes? – Private Classes class deathwatch { public static function monitor($object, Closure $callback) { $keyName = 'monitor' . spl_object_hash($object); $monitor = new class($callback) { protected $callback; public function __construct($callback) { $this->callback = $callback; } public function __destruct() { $callback = $this->callback; $callback(); } }; $object->$keyName = $monitor; } }
  • 22. PHP7 Anonymous Classes • Why would I use Anonymous Classes? – Private Classes class character { protected $name; public function __construct($name) { $this->name = $name; } } $characters = [ new character('Ned Stark'), new character('Olenna Tyrell'), new character('Tywin Lannister'), new character('Myrcella Baratheon'), ];
  • 23. PHP7 Anonymous Classes • Why would I use Anonymous Classes? – Private Classes deathwatch::monitor($characters[0], function() { echo 'Oh noes', PHP_EOL; }); deathwatch::monitor($characters[1], function() { echo 'Oh yaes', PHP_EOL; }); deathwatch::monitor($characters[2], function() { echo 'Oh no, not again!', PHP_EOL; }); unset($characters[0], $characters[1]); echo PHP_EOL, '---===---', PHP_EOL, PHP_EOL;
  • 24. PHP7 Anonymous Classes • Why would I use Anonymous Classes? – Private Classes Oh noes Oh yaes ---===--- Oh no, not again!
  • 25. PHP7 Anonymous Classes • Why would I use Anonymous Classes? – Test Mocking • https://mfyu.co.uk/post/anonymous-classes-in-php-7-are-fantastic-for-tests
  • 26. PHP7 Anonymous Classes • Inner- or Nested-Classes class SpyMaster { private $targetObject; protected $objectMission; public function __construct($targetObject) { $this->targetObject = $targetObject; $this->objectMission = new SpyObjectMission($targetObject); } protected function getHandler() { … } public function infiltrate() { return $this->getHandler(); } }
  • 27. PHP7 Anonymous Classes • Inner- or Nested-Classes class SpyObjectMission { public $methods = []; public $invoker; public function __construct($targetObject) { $reflector = new ReflectionObject($targetObject); $this->invoker = $this->getInvoker($reflector, $targetObject); } protected function getInvoker(ReflectionObject $reflector, $targetObject) { $staticMethods = array_column($reflector->getMethods(ReflectionMethod::IS_STATIC), 'name'); $this->methods = array_diff( array_column($reflector->getMethods(), 'name'), $staticMethods) ); $invoker = function($methodName, ...$args) { return self::$methodName(...$args); }; return $invoker->bindTo($targetObject, get_class($targetObject)); } }
  • 28. PHP7 Anonymous Classes • Inner- or Nested-Classes protected function getHandler() { return new class ($this->objectMission) { private $objectMission; public function __construct(SpyObjectMission $objectMission) { $this->objectMission = $objectMission; } public function __call($methodName, $args) { if (in_array($methodName, $this->objectMission->methods)) { $invoker = $this->objectMission->invoker; return $invoker($methodName, ...$args); } throw new Exception("Object Method {$methodName} does not exist"); } }; }
  • 29. PHP7 Anonymous Classes • Inner- or Nested-Classes $test = new classThatWeWantToTest(1, 2, 3); $spy = (new SpyMaster($test)) ->infiltrate(); echo 'SPY FOR TEST #1', PHP_EOL; echo $spy->privateMethodThatWeWantToTest(), PHP_EOL;
  • 30. PHP7 Anonymous Classes • Inner- or Nested-Classes • Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 2) • https://markbakeruk.net/2017/07/30/closures-anonymous-classes-and-an-alternative- approach-to-test-mocking-part-2/ • Closures, Anonymous Classes and an alternative approach to Test Mocking (Part 4) • https://markbakeruk.net/2018/01/23/closures-anonymous-classes-and-an-alternative- approach-to-test-mocking-part-4/
  • 32. Who am I? Mark Baker @Mark_Baker https://github.com/MarkBaker http://uk.linkedin.com/pub/mark-baker/b/572/171 http://markbakeruk.net