An Elephant of a Different Colour: Hack

67 %
33 %
Information about An Elephant of a Different Colour: Hack
Technology

Published on March 5, 2014

Author: zymsys

Source: slideshare.net

Description

Slides from my GTA-PHP Meetup talk about Hack which is the Facebook version of the PHP programming language which runs under their HHVM runtime environment for PHP. The focus of my talk was the language improvements that the Facebook team has added to PHP.

There's a lot of information in the presenter's notes, so if you're interested in Hack scroll down to see the extras.

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/

Add a comment

Comments

ba92v4p7yq | 12/09/15
 閫欑ó妯″紡鍑虹従鏂?988骞?鎴戞兂鎴戠殑闆欒優鑳庡悎娉曠殑绱堢禎瀛愬紵锛屼粬 鏈堜寒婧栧倷鏉愭枡锛屾垜鍠滄浠栧€戝浣曞湪 S鎳夎┎鏄儚鍙告 浣嗙暙闈㈠懠姘f脯瑭︾▼搴?   闁嬮棦浜嗚警璜栵紝鍏浉绫嶅痉瑗?S涓嶅€笉椤?涓湅瑁介€犵殑鍫撮潰浼间箮閫欏€嬪唬鍛?   娉曞畼鑾浄鎷変綆闊筹紝浣?浣犲緱鍒?浣犵煡閬撳惞鍣撳畠涓嶆槸瑾湅鎴戞湁浠€楹?  
vq96g0h9zd | 13/09/15
 浣犲緢濂斤紝鎴戣寰楀畠 绠牠鏋滀綘鍦ㄥ摢瑁℃垨鑰呭嵆灏囩湅鍒版垜鍊戠殑鍋氭硶瑕栭牷 鍣稿繕浜嗗枩姝″拰鍠滄剾鐨?鐧艰劸姘e拰缇庡姘寸檪涓績閫欐槸RPF 鑸囧叾浠栭亱鍕曢瀷瑕栭牷鍞?   鏂借彲娲涗笘濂?鐝惧湪閫欏氨鏄偤浠€楹兼湁鎿旀灦锛岄€欐槸绗竴鐧?鎴戠涓€娆℃湁瀹冩敼璁婁簡鎴戠殑鐢熸椿   娣峰悎matuto鏃㈠鎻氬皬蹇冪櫦鐢熼€欑ó鎯呮硜锛屼綘鐨勫敮涓€浜嬩欢 椋汧ARC鐨勯殜浼嶄腑鍘诲悜鍏?瑭插埌浜嗛偅瑁¢€欎簺鑲畾娌?  

Related presentations

Related pages

Upcoming Events | An Elephant of a Different Colour: Hack

Visit the post for more. ... An Elephant of a Different Colour: Hack. Tuesday, Mar 4, 2014, 7:00 PM. Jobspring Toronto
Read more

Elephant-Games

Copyright 2016 Elephant Games. All rights reserved. ...
Read more

Elephant Information | Knysna Elephant Park

General Elephant Information ... dwelling animals should be classified as a different species of elephant. ... weapons and hack off their tusks ...
Read more

Automated Elephant-detection system • Hackaday.io

I've outlined the different ... elephants are large and they are a distinct colour, ... You are about to report the project "Automated Elephant ...
Read more

Deilephila elpenor - Wikipedia

Deilephila elpenor, known as the elephant hawk-moth, ... green and brown in colour. ... Its eye includes two different kinds of ommatidium; ...
Read more

Animals | Colblindor - Color Blindness

Our color vision is based on three different types of visual pigments. ... Animals have either only one ... And why the hack are there still so many color ...
Read more

Glidden Paint - Paint Colors And Paint Palettes | Glidden.com

If you're looking for exterior paint colors, or paint colors that go well with your home's interior decor, you're in the right place. There are many colors ...
Read more

iCloud

iCloud makes sure you always have the latest versions of your most important things — documents, photos, notes, contacts, and more — on all your devices.
Read more

Berlin Mag

© 2016 by bring the pixel. Remember to change this. Back to Top
Read more