SlideShare una empresa de Scribd logo
1 de 30
An Elephant of a Different Colour: Hack

Reduce your Server Load, Reuse your Code and
Recycle your PHP Skills with HHVM & Hack
Image Copyright Keith Evans. This work is licensed under the Creative Commons Attribution-Share Alike 2.0 Generic Licence. To view a copy of this licence,
visit http://creativecommons.org/licenses/by-sa/2.0/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
Just in case you’re not up to
speed on this HHVM stuff…

© Some rights reserved by Dave Hamster

© Some rights reserved by Andy Barnes

© Some rights reserved by Casey Fleser
Hack

Collection
Lambd
Type
Async
XHP
a
s
XHP

<?hh
require_once('lib/init.php');
$class = "greeting";
$subject = "Toronto & area";
$body = <p class={$class}>$hello {ucwords($subject)}</p>;
echo <x:doctype>
<html>
<head><title>Hello XHP</title></head>
<body>{$body}</body>
</html>
<!DOCTYPE html>
</x:doctype>;
<html>

<head><title>Hello XHP</title></head>
<body>
<p class="greeting">$hello Toronto &amp; Area</p>
</body>
</html>
XHP

<?hh
require_once('lib/init.php');
$list = <ul />;
for ($i = 0; $i < 7; $i += 1) {
$list->appendChild(<li>{date('l', time() + $i * 86400)}</li>);
}
<ul>
echo $list;
XHP emits HTML without
the whitespace and
formatting. I’ve added it
for readability.

<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
<li>Thursday</li>
<li>Friday</li>
<li>Saturday</li>
<li>Sunday</li>
</ul>
XHP
•

Available for Zend PHP too!

•

See https://github.com/facebook/xhp

•

Can use HTML() to emit unescaped HTML but
don’t.
Collections
Vecto
r
0 => ‘Apples’,
1 => ‘Bananas’,
2 => ‘Oranges’

Ma
p
[Red] => ‘Apples’,
[Yellow] => ‘Bananas’,
[Orange] => ‘Oranges’

Se
t

Pai
r
0 => ‘Apples’,
1 => ‘Bananas’

‘Apples’,
‘Bananas’
‘Oranges’
Vectors
<?hh
$v = Vector { "zero", "one" };
$v[] = 2;
$v->add($v->count());
$v->removeKey(0);
print_r($v);

[0] => "zero"
[1] => “one”
[0] => "zero"
[1] => "one"
[2] => 2
[0] => "zero"
[1] => "one"
[2] => 2
[3] => 3
[0] => “one"
[1] => 2
[2] => 3
Old School Arrays

<?php
$v = array("zero", “one”);

[0] => “zero"
[1] => “one"

$v[] = 2;

[0] => "zero"
[1] => "one"
[2] => 2

array_push($v, count($v));
unset($v[0]);
print_r($v);
Can you spot the difference between
the Hack and PHP results?

[0] => "zero"
[1] => "one"
[2] => 2
[3] => 3
[1] => "one"
[2] => 2
[3] => 3
Vectors
•

Always 0 .. (count -1)

•

Values are not hashed / indexed
•

•

Use Sets for this

Can use [] to append, but not unset() to remove
Pair
<?hh
require_once('../lib/init.php');
$dynamicDuo = Pair {'Batman', 'Robin'};
$p = Pair {$dynamicDuo, <p>The dynamic Duo</p>};
print_r($p);

Pair Object
(
[0] => Pair Object
(
[0] => Batman
[1] => Robin
)
[1] => xhp_p Object
(
[tagName:protected] => p
[attributes:xhp_x__composable_element:private] => Array
()
[children:xhp_x__composable_element:private] => Array
(
[0] => The dynamic Duo
)
[source] => /home/vic/prog/presentation/collections/pair.php:4
)
)
Pair
•

Pairs must contain two items of any type

•

Pairs are always immutable

•

Items are accessed with [0] and [1]
Map
<?hh
$map = Map {
'CA' => 'Canada',
'US' => 'United States'
};
Map Object
$map->add(Pair {'MX', 'Mexico'}); (
$map['NI'] = 'Nicaragua';
[CA] => Canada
print_r($map);

)

[US] => United States
[MX] => Mexico
[NI] => Nicaragua
Map
•

Maps contain key / value Pairs

•

Keys can only be integers or strings

•

Values can be of any type

•

Order is preserved
Set

<?hh
$s = Set {'US', 'CA'};
$s->add('MX');
$s[] = 'NI';
$s[] = ($s->contains('CA') ? 'Has' : 'Lacks') . ' Canada';
print_r($s);
•

Can only contain integers or
strings

•

Unordered

HHSet Object
(
US
CA
MX
NI
Has Canada
)
Types
<?hh
function add(int $a, int $b): int {
return $a + $b;
}
var_dump(add(1, 2));
var_dump(add(1.5, 2));
int(3)
HipHop Fatal error: Argument 1 passed to add() must be an
instance of int, double given in
/home/vic/prog/presentation/type.php on line 4
Types
<?hh
function add(
shape('x' => int, 'y' => int) $p1,
shape('x' => int, 'y' => int) $p2
): shape('x' => int, 'y' => int) {
return shape(‘x' => $p1['x'] + $p2['x'], 'y' => $p1['y'] + $p2[‘y']);
}
var_dump(add(['x' => 3, 'y' => 4], ['x' => 5, 'y' => 25]));

array(2) {
["x"]=>int(8)
["y"]=>int(29)
}
Types

<?hh
type Coord = shape('x' => int, 'y' => int);
function add(Coord $p1, Coord $p2): Coord {
return ['x' => $p1['x'] + $p2['x'], 'y' => $p1['y'] + $p2['y']];
}
var_dump(add(['x' => 3, 'y' => 4, 'z' => 1], ['x' => 5, 'y' =>
25]));
var_dump(add(['x' => 3, 'z' => 4], ['x' => 5, 'y' => 25]));

array(2) {[“x”]=>int(8), [“y"]=>int(29)}
HipHop Notice: Undefined index: y in
/home/vic/prog/presentation/typedef.php on line 4
array(2) {[“x”]=>int(8), ["y"]=>int(25)}
Generics

<?hh
class Accumulator<T> {
function __construct(private T $value) {}
function add(T $value) { $this->value += $value; }
function get():T { return $this->value; }
}
$accumulateInts = new Accumulator<int>(5);
$accumulateInts->add(4);
var_dump($accumulateInts->get());
$accumulateFloats = new Accumulator<float>(0.7);
$accumulateFloats->add(1.6);
var_dump($accumulateFloats->get());
$accumulate = new Accumulator([5]);
$accumulate->add([4,9]);
var_dump($accumulate->get());

int(9)

float(2.3)
array(2) {
[0]=>int(5)
[1]=>int(9)
}
Generics

<?hh
class Accumulator<T> {
function __construct(private T $value) {}
function add(T $value) { $this->value += $value; }
function get():T { return $this->value; }
}
$accumulateInts = new Accumulator<int>(5);
$accumulateInts->add(4);
$accumulateInts->add(4.4);
var_dump($accumulateInts->get());
float(13.4
)

!
Nullable Types
<?hh
function printNum(?int $num) {
echo "num is ";
echo is_null($num) ? "null" : $num;
echo "n";
num is 1
}
num is null
printNum(1);
HipHop Warning: Argument 1 to
printNum(null);
printNum() must be of type ?int,
printNum("Five");
string given in
/home/vic/prog/presentation/nullabl
e.php on line 6
num is Five
Types
<?hh
class MyClass<T as SomeInterface> {
function __construct(private T $v) {}
}
newtype Secret as BaseClass =
MyClass;
Lambda

<?php
$countries = [
'US' => 'United States',
'CA' => 'Canada',
'MX' => 'Mexico',
];
uasort($countries, function ($a, $b) {
return $a > $b;
array(3) {
});
["CA"]=>
string(6) "Canada"
var_dump($countries);

}

["MX"]=>
string(6) "Mexico"
["US"]=>
string(13) "United States"
Lambda

<?hh
$countries = [
'US' => 'United States',
'CA' => 'Canada',
'MX' => 'Mexico',
];
uasort($countries, ($a, $b) ==> $a >
$b);
array(3) {
var_dump($countries);

}

["CA"]=>
string(6) "Canada"
["MX"]=>
string(6) "Mexico"
["US"]=>
string(13) "United States"
Lambda
<?hh
$add = ($a, $b) ==> $a + $b;
function curry($callable, $value) {
return $v ==> $callable($value, $v);
}
$addFour = curry($add, 4);
var_dump($addFour(5));

int(9)
User Attributes
Array
(
[MyAnnotation] => Array
(
[0] => Unicorn
[1] => 42
)
$rc = new ReflectionFunction('bar');
print_r($rc->getAttributes());
)
<?hh
<< MyAnnotation('Unicorn',
42) >>
function bar() {
}
User Attributes
•

You can add attributes / annotations to classes,
methods, functions and arguments.

•

You can specify more than one set of user
attributes:
<< Foo(1), Bar(2) >>

•

You can’t use constants or variables in attributes
Async
•

I lied; hhvm’s async is more c# than node.

•

Library functions like evhttp_async_get() don’t
return Awaitable’s
•

•

So they don’t seem to play well together

PocketRent/beatbox uses async, but I don’t grock it
class Foo{}

Async

class Bar {
public function getFoo(): Foo {
return new Foo();
}
}

This is the example
Facebook provided
on GitHub for async.

async function gen_foo(int $a): Awaitable<?Foo> {
if ($a === 0) {
return null;
}
$bar = await gen_bar($a);
if ($bar !== null) {
return $bar->getFoo();
}
}

return null;

async function gen_bar(int $a): Awaitable<?Bar> {
if ($a === 0) {
return null;
}
}

return new Bar();

gen_foo(4);
More
•

See hhvm.com

•

The debugger is command line, and very good:
hhvm -m debug

•

Sara Golemon is giving a talk tomorrow night about HHVM and
hack, and it will be live streamed:
http://www.meetup.com/sf-php/events/159404382/

•

Framework for Hack:
https://wiki.pocketrent.com/beatbox/start

•

I promise to blog about Hack at http://blog.vicmetcalfe.com/

Más contenido relacionado

La actualidad más candente

Functional Pe(a)rls version 2
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2osfameron
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in OptimizationDavid Golden
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHPGuilherme Blanco
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixturesBill Chang
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기Suyeol Jeon
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Evgeny Borisov
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?Nikita Popov
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome TownRoss Tuck
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersIan Barber
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionIan Barber
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks Damien Seguy
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 

La actualidad más candente (20)

Functional Pe(a)rls version 2
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
PHP 5.4
PHP 5.4PHP 5.4
PHP 5.4
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2Groovy puzzlers jug-moscow-part 2
Groovy puzzlers jug-moscow-part 2
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 

Destacado

Organizing Your PHP Projects (2010 ConFoo)
Organizing Your PHP Projects (2010 ConFoo)Organizing Your PHP Projects (2010 ConFoo)
Organizing Your PHP Projects (2010 ConFoo)Paul Jones
 
Namespaces and Autoloading
Namespaces and AutoloadingNamespaces and Autoloading
Namespaces and AutoloadingVic Metcalfe
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutVic Metcalfe
 

Destacado (6)

Organizing Your PHP Projects (2010 ConFoo)
Organizing Your PHP Projects (2010 ConFoo)Organizing Your PHP Projects (2010 ConFoo)
Organizing Your PHP Projects (2010 ConFoo)
 
New in php 7
New in php 7New in php 7
New in php 7
 
Namespaces and Autoloading
Namespaces and AutoloadingNamespaces and Autoloading
Namespaces and Autoloading
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and Knockout
 
Getting hands dirty with php7
Getting hands dirty with php7Getting hands dirty with php7
Getting hands dirty with php7
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 

Similar a An Elephant of a Different Colour: Hack

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6garux
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked aboutTatsuhiko Miyagawa
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)MongoSF
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netProgrammer Blog
 
PHP record- with all programs and output
PHP record- with all programs and outputPHP record- with all programs and output
PHP record- with all programs and outputKavithaK23
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterRicardo Signes
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Workhorse Computing
 

Similar a An Elephant of a Different Colour: Hack (20)

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Php functions
Php functionsPhp functions
Php functions
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 
20 modules i haven't yet talked about
20 modules i haven't yet talked about20 modules i haven't yet talked about
20 modules i haven't yet talked about
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
PHP Tutorial (funtion)
PHP Tutorial (funtion)PHP Tutorial (funtion)
PHP Tutorial (funtion)
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
PHP record- with all programs and output
PHP record- with all programs and outputPHP record- with all programs and output
PHP record- with all programs and output
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Crafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::ExporterCrafting Custom Interfaces with Sub::Exporter
Crafting Custom Interfaces with Sub::Exporter
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
 

Último

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 

Último (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 

An Elephant of a Different Colour: Hack

  • 1. An Elephant of a Different Colour: Hack Reduce your Server Load, Reuse your Code and Recycle your PHP Skills with HHVM & Hack Image Copyright Keith Evans. This work is licensed under the Creative Commons Attribution-Share Alike 2.0 Generic Licence. To view a copy of this licence, visit http://creativecommons.org/licenses/by-sa/2.0/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
  • 2. Just in case you’re not up to speed on this HHVM stuff… © Some rights reserved by Dave Hamster © Some rights reserved by Andy Barnes © Some rights reserved by Casey Fleser
  • 4. XHP <?hh require_once('lib/init.php'); $class = "greeting"; $subject = "Toronto & area"; $body = <p class={$class}>$hello {ucwords($subject)}</p>; echo <x:doctype> <html> <head><title>Hello XHP</title></head> <body>{$body}</body> </html> <!DOCTYPE html> </x:doctype>; <html> <head><title>Hello XHP</title></head> <body> <p class="greeting">$hello Toronto &amp; Area</p> </body> </html>
  • 5. XHP <?hh require_once('lib/init.php'); $list = <ul />; for ($i = 0; $i < 7; $i += 1) { $list->appendChild(<li>{date('l', time() + $i * 86400)}</li>); } <ul> echo $list; XHP emits HTML without the whitespace and formatting. I’ve added it for readability. <li>Monday</li> <li>Tuesday</li> <li>Wednesday</li> <li>Thursday</li> <li>Friday</li> <li>Saturday</li> <li>Sunday</li> </ul>
  • 6. XHP • Available for Zend PHP too! • See https://github.com/facebook/xhp • Can use HTML() to emit unescaped HTML but don’t.
  • 7. Collections Vecto r 0 => ‘Apples’, 1 => ‘Bananas’, 2 => ‘Oranges’ Ma p [Red] => ‘Apples’, [Yellow] => ‘Bananas’, [Orange] => ‘Oranges’ Se t Pai r 0 => ‘Apples’, 1 => ‘Bananas’ ‘Apples’, ‘Bananas’ ‘Oranges’
  • 8. Vectors <?hh $v = Vector { "zero", "one" }; $v[] = 2; $v->add($v->count()); $v->removeKey(0); print_r($v); [0] => "zero" [1] => “one” [0] => "zero" [1] => "one" [2] => 2 [0] => "zero" [1] => "one" [2] => 2 [3] => 3 [0] => “one" [1] => 2 [2] => 3
  • 9. Old School Arrays <?php $v = array("zero", “one”); [0] => “zero" [1] => “one" $v[] = 2; [0] => "zero" [1] => "one" [2] => 2 array_push($v, count($v)); unset($v[0]); print_r($v); Can you spot the difference between the Hack and PHP results? [0] => "zero" [1] => "one" [2] => 2 [3] => 3 [1] => "one" [2] => 2 [3] => 3
  • 10. Vectors • Always 0 .. (count -1) • Values are not hashed / indexed • • Use Sets for this Can use [] to append, but not unset() to remove
  • 11. Pair <?hh require_once('../lib/init.php'); $dynamicDuo = Pair {'Batman', 'Robin'}; $p = Pair {$dynamicDuo, <p>The dynamic Duo</p>}; print_r($p); Pair Object ( [0] => Pair Object ( [0] => Batman [1] => Robin ) [1] => xhp_p Object ( [tagName:protected] => p [attributes:xhp_x__composable_element:private] => Array () [children:xhp_x__composable_element:private] => Array ( [0] => The dynamic Duo ) [source] => /home/vic/prog/presentation/collections/pair.php:4 ) )
  • 12. Pair • Pairs must contain two items of any type • Pairs are always immutable • Items are accessed with [0] and [1]
  • 13. Map <?hh $map = Map { 'CA' => 'Canada', 'US' => 'United States' }; Map Object $map->add(Pair {'MX', 'Mexico'}); ( $map['NI'] = 'Nicaragua'; [CA] => Canada print_r($map); ) [US] => United States [MX] => Mexico [NI] => Nicaragua
  • 14. Map • Maps contain key / value Pairs • Keys can only be integers or strings • Values can be of any type • Order is preserved
  • 15. Set <?hh $s = Set {'US', 'CA'}; $s->add('MX'); $s[] = 'NI'; $s[] = ($s->contains('CA') ? 'Has' : 'Lacks') . ' Canada'; print_r($s); • Can only contain integers or strings • Unordered HHSet Object ( US CA MX NI Has Canada )
  • 16. Types <?hh function add(int $a, int $b): int { return $a + $b; } var_dump(add(1, 2)); var_dump(add(1.5, 2)); int(3) HipHop Fatal error: Argument 1 passed to add() must be an instance of int, double given in /home/vic/prog/presentation/type.php on line 4
  • 17. Types <?hh function add( shape('x' => int, 'y' => int) $p1, shape('x' => int, 'y' => int) $p2 ): shape('x' => int, 'y' => int) { return shape(‘x' => $p1['x'] + $p2['x'], 'y' => $p1['y'] + $p2[‘y']); } var_dump(add(['x' => 3, 'y' => 4], ['x' => 5, 'y' => 25])); array(2) { ["x"]=>int(8) ["y"]=>int(29) }
  • 18. Types <?hh type Coord = shape('x' => int, 'y' => int); function add(Coord $p1, Coord $p2): Coord { return ['x' => $p1['x'] + $p2['x'], 'y' => $p1['y'] + $p2['y']]; } var_dump(add(['x' => 3, 'y' => 4, 'z' => 1], ['x' => 5, 'y' => 25])); var_dump(add(['x' => 3, 'z' => 4], ['x' => 5, 'y' => 25])); array(2) {[“x”]=>int(8), [“y"]=>int(29)} HipHop Notice: Undefined index: y in /home/vic/prog/presentation/typedef.php on line 4 array(2) {[“x”]=>int(8), ["y"]=>int(25)}
  • 19. Generics <?hh class Accumulator<T> { function __construct(private T $value) {} function add(T $value) { $this->value += $value; } function get():T { return $this->value; } } $accumulateInts = new Accumulator<int>(5); $accumulateInts->add(4); var_dump($accumulateInts->get()); $accumulateFloats = new Accumulator<float>(0.7); $accumulateFloats->add(1.6); var_dump($accumulateFloats->get()); $accumulate = new Accumulator([5]); $accumulate->add([4,9]); var_dump($accumulate->get()); int(9) float(2.3) array(2) { [0]=>int(5) [1]=>int(9) }
  • 20. Generics <?hh class Accumulator<T> { function __construct(private T $value) {} function add(T $value) { $this->value += $value; } function get():T { return $this->value; } } $accumulateInts = new Accumulator<int>(5); $accumulateInts->add(4); $accumulateInts->add(4.4); var_dump($accumulateInts->get()); float(13.4 ) !
  • 21. Nullable Types <?hh function printNum(?int $num) { echo "num is "; echo is_null($num) ? "null" : $num; echo "n"; num is 1 } num is null printNum(1); HipHop Warning: Argument 1 to printNum(null); printNum() must be of type ?int, printNum("Five"); string given in /home/vic/prog/presentation/nullabl e.php on line 6 num is Five
  • 22. Types <?hh class MyClass<T as SomeInterface> { function __construct(private T $v) {} } newtype Secret as BaseClass = MyClass;
  • 23. Lambda <?php $countries = [ 'US' => 'United States', 'CA' => 'Canada', 'MX' => 'Mexico', ]; uasort($countries, function ($a, $b) { return $a > $b; array(3) { }); ["CA"]=> string(6) "Canada" var_dump($countries); } ["MX"]=> string(6) "Mexico" ["US"]=> string(13) "United States"
  • 24. Lambda <?hh $countries = [ 'US' => 'United States', 'CA' => 'Canada', 'MX' => 'Mexico', ]; uasort($countries, ($a, $b) ==> $a > $b); array(3) { var_dump($countries); } ["CA"]=> string(6) "Canada" ["MX"]=> string(6) "Mexico" ["US"]=> string(13) "United States"
  • 25. Lambda <?hh $add = ($a, $b) ==> $a + $b; function curry($callable, $value) { return $v ==> $callable($value, $v); } $addFour = curry($add, 4); var_dump($addFour(5)); int(9)
  • 26. User Attributes Array ( [MyAnnotation] => Array ( [0] => Unicorn [1] => 42 ) $rc = new ReflectionFunction('bar'); print_r($rc->getAttributes()); ) <?hh << MyAnnotation('Unicorn', 42) >> function bar() { }
  • 27. User Attributes • You can add attributes / annotations to classes, methods, functions and arguments. • You can specify more than one set of user attributes: << Foo(1), Bar(2) >> • You can’t use constants or variables in attributes
  • 28. Async • I lied; hhvm’s async is more c# than node. • Library functions like evhttp_async_get() don’t return Awaitable’s • • So they don’t seem to play well together PocketRent/beatbox uses async, but I don’t grock it
  • 29. class Foo{} Async class Bar { public function getFoo(): Foo { return new Foo(); } } This is the example Facebook provided on GitHub for async. async function gen_foo(int $a): Awaitable<?Foo> { if ($a === 0) { return null; } $bar = await gen_bar($a); if ($bar !== null) { return $bar->getFoo(); } } return null; async function gen_bar(int $a): Awaitable<?Bar> { if ($a === 0) { return null; } } return new Bar(); gen_foo(4);
  • 30. More • See hhvm.com • The debugger is command line, and very good: hhvm -m debug • Sara Golemon is giving a talk tomorrow night about HHVM and hack, and it will be live streamed: http://www.meetup.com/sf-php/events/159404382/ • Framework for Hack: https://wiki.pocketrent.com/beatbox/start • I promise to blog about Hack at http://blog.vicmetcalfe.com/

Notas del editor

  1. Ask audience what they think each photo represents. Some of the HHVM Team: Comes from Facebook, Facebook runs on HHVM. HHVM’s primary goal is speed, and it is very fast Silk Street in Beijing, famous for knock-off fasions. HHVM closely duplicates Zend’s PHP interpreter. Evolution of technology. HHVM’s Hack takes PHP language to the next level.
  2. Require init.php {$x} notation for substitution Escapes values Allows expressions including function calls, etc No quotes for attributes No substitution without {} Special &amp;lt;x:doctype&amp;gt; element
  3. Cool, we can use [] to -&amp;gt;add() Cool, we can remove items with removeKey() Boo, we can’t remove items with unset()
  4. Vector re-indexing on removeKey vs no re-indexing on Array. I prefer to know that an array is zero based or not based on its type
  5. Pairs can contain any two items XHP is interesting (and out of place) here
  6. Yes! You can use [] to add a Pair as shorthand for -&amp;gt;add()
  7. Type hints for primitive types! Types are (sometimes) enforced!
  8. Shapes are like typed arrays which specify legal keys Return shape() returns an array Shapes map to arrays, not to Maps which are Map objects. Wait for someone to say “Can’t you typedef?” before next slide
  9. Hurray typedef! Extra keys are ignored Missing keys DON’T CAUSE AN ERROR until you try to use the key Any advantage to shapes over arrays? I don’t know. Hopefully shape mismatches can be caught in the future as type errors.
  10. Constructor shorthand The rest pretty well speaks for itself
  11. Type information doesn’t seem to be used at runtime. Debugger doesn’t show type of value. Rewriting without generics or type info yields same behaviour. Is there a point to having generics if they don’t enforce types? My tests didn’t show improved speed with generics over typeless either. Hopefully these before enforced down the road
  12. Appears to be partially implemented / future features here. as should probably constrain types to a given superclass or interface, but currently appear to do nothing newtype will hide type information outside of the file it is declared in according to Joel Marcey (https://github.com/facebook/hhvm/issues/1846)
  13. Review: Plain old PHP anonymous functions
  14. No function keyword, no return statement, no curly brackets! Curly brackets and return statement are optional If only one parameter brackets are optional
  15. No need for use clauses! Access to variables in scope are preserved
  16. Node minimizes CPU context switching to achieve high performance hhvm still uses threading extensively and is not ‘evented’
  17. Node minimizes CPU context switching to achieve high performance hhvm still uses threading extensively and is not ‘evented’