elephant-taming-talk



elephant-taming-talk

0 0


elephant-taming-talk


On Github 1stvamp / elephant-taming-talk

Elephant taming for snake lovers

aka PHP for pythonistas

Wes Mason

@1stvamp

Who?

  • / @1stvamp
  • Online services, Canonical
  • Open source
  • Former publisher of PHP Weekly

PHP

  • Dynamic/interpreted language
  • Web applications
  • OO, functional
  • "Personal HomePage"
  • Bad reputation
  • Extremely popular

Differences

  • Braces, semi-colons, mostly-ignored whitespace (C family)
  • Special variable symbol ($)
  • Heavily (populated | polluted) global namespace

More differences

  • Geared towards file-based inclusion (anyone remember SSI?)
  • Web server inbuilt functions and globals
  • Loosely typed, with scalar types

C-stylee

<?php
$foo = true;

// Let's check $foo!
if ($foo) {
/**
 * I guess $foo was TRUE!
 */
echo 'Hello World';
}

# Ambiguity? I barely know her.
print('Goodbye');
exit(0);

Variables

<?php
$foo = 'bar';
$baz = $foo;
$test = [];
define('MY_CONSTANT', 'hello world');
echo MY_CONSTANT;

Global namespace

  • 9,541 global functions and methods listed on docs.php.net
  • 4,559 of these are functions without a containing class
  • Many of which rely on extensions (e.g. Apache, APC, MySQL etc.)
  • 99 of which are in a namespace

Meanwhile in Python..

$ python3
Python 3.4.3 (default, Mar 26 2015, 22:03:40) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> len(dir(__builtins__))
148

Files all the way down

  • include, include_once, require, require_once
  • Namespaces (modules) are "syntax sugar", you can declare more than in a single file
  • Importing namespaces is done either manually (e.g. require), or with user-space autoload hooks

Beginner friendly bootstrapping

  • echo '<?php print "Hello world";' > index.php
  • scp index.php my_server:~/public_html
  • Open my_server/index.php in a browser.
  • Hit the pub and declare you're a developer.

No WSGI, no worries

  • WSGI makes sense from an engineering perspective
  • Enhances maintenance of large ongoing projects
  • Provides a standard API that all frameworks and app runners speak

Meanwhile, in PHP-land..

  • PHP includes a massive array of functions, variables, constants, and even some APIs for web dev.
  • header(), move_uploaded_file(), http_digest_parse(), etc.

in PHP-land cont.

  • $_GET, $_POST, $_REQUEST, $_FILES etc.
  • This easy boostrap and deployment story makes writing an app fun for beginners.

Similarities

simildifferities? Diffelarities? Similirences?

  • An "everything and the kitchen sink" philosophy
  • ..serialize (like pickle), json, file reading, gzip/zip handling, mail sending, databases, etc.
  • Namespaces (packages and modules)

Similarities cont.

  • Type hinting (similar to PEP-484)
  • Exceptions
  • Rich data-types...kinda...ok...usually just one, but it's very rich.

Similarities cont.

  • Lambdas, variable scoping, generators, functional helpers
  • Availability (pretty much everywhere, including Windows)
  • Healthy userspace libraries in a repository (packagist.org, the PHP'ers cheeseshop)

Generators

<?php
function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
     }
}

Namespaces

Note: Namespaces uses the \ separator, e.g.

<?php
namespace 'wesmason';
class Foo {
}

namespace 'wesmason\bar';
class Baz {
}

Namespaces cont.

<?php
$foo = new wesmason\Foo;
$baz = new wesmason\Bar\Baz();

Autoloading

<?php
function __autoload($class_name) {
    include $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 

Autoloading cont.

<?php
function __autoload($name) {
    $parts = explode($name, '\\');
    require $parts[0];
}

The Almight Array

  • Workhorse of PHP datatypes
  • tuple, namedtuple, list, dict and OrderedDict, all rolled into one

array()

<?php
$foo = array(1, 2, 'bar');
$baz = [ 'fred' => 42, 'velma' => 50 ];
assert(in_array('velma', $foo) === false);
assert(in_array('fred', $baz) === true);

Composer

pip for PHP

  • composer install wordpress==x.x.x
  • packagist.org
  • Pinning (and vendoring)
  • JSON package metadata format

composer.json

{
    "name": "wilgucki/csv",
    "description": "Laravel 5 package for writing and reading CSV files",
    "keywords": ["Laravel", "csv"],
    "license": "MIT",
    "authors": [
        {
            "name": "Maciej Wilgucki",
            "email": "mwilgucki+packagist@gmail.com"
        }
    ],
    "require": {
        "php": ">=5.5.0"
    },
    "autoload": {
            "psr-4": {
            "Wilgucki\\Csv\\": "src"
        }
    }
}

Autoloaders

Note: That damned \ again, e.g.

{
     "autoload": {
      "psr-4": {"Acme\\": "src/"}
     }
}

XDebug

  • Remote debugger, with breakpoints, stepping, strack introspection etc. (think PDB or Celerys rdb)
  • Profiler (think cProfile)

XDebug cont.

  • Remote debugging network protocol, with a bunch of clients (including inbuilt support in IDEs)
  • PHP C extension, with xdebug_* functions to call breakpoints, set profile timers etc.

Helper functions

<?php
$debug_function = function() {
echo xdebug_call_function();
};

Speaking of debugging..

..what about a REPL?

boris

$ composer global install "d11wtq/boris"
$ export PATH="$PATH:~/.composer/vendor/bin/"
...
$ boris

boris cont.

$ boris
[1] boris> $test = ['foo', 'bar', 'baz'];
// array(
//   0 => 'foo',
//   1 => 'bar',
//   2 => 'baz'
// )
[2] boris> foreach($test as $t) { 
[2]     *> echo $t . "\n";
[2]     *> }
foo
bar
baz
[3] boris> ^D

docs.php.net

  • http://php.net/function-name-here
  • Large project in a git repo, with build files, translations, examples etc.
  • Having a large global namespace means having GOOD documention.

Migratin'

  • Long ramp up period between PHP4 and PHP5, lots of breakages
  • Majority of open source projects now on 5
  • Good support for new releases on non-cloudy-hosts

What year is it, who's the president?

  • PHP 7 - faster, return type hinting, AST, some breakages
  • HHVM - JIT based runtime, compatible with PHP 5 (ish)

Hand me my flux capacitor

  • HippyVM - RPython implementation of PHP, e.g. it runs on PyPy
  • Hack - fork based on HHVM engine, with extra language features that aren't compatible

Talking about versions..

Talking about (more) versions..

sys.exit(0)

^D