Skip to content

Instantly share code, notes, and snippets.

@noodlehaus
Last active August 10, 2017 14:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noodlehaus/1e316ae659a74c8cf788 to your computer and use it in GitHub Desktop.
Save noodlehaus/1e316ae659a74c8cf788 to your computer and use it in GitHub Desktop.
Some patterns I use in plain old PHP apps

pulling values from arrays

$name = @$_POST['name'];
# => null or the value for name

defaults for associative arrays

function connect($provided) {
  $defaults = [
    'host' => 'localhost',
    'port' => 8000
  ];
  $config = $provided + $defaults;
  return some_func($config['host'], $config['port']);
}

$connection = connect([
  'host' => 'some.app.server-host.com',
  'port' => 9999
]);
# => falls back to localhost:8000 if config is insufficient

creating hash of empty values

$defaults = array_fill_keys(['username', 'email'], '');
# => creates a hash with passed keys having blank values

pulling values from hash and using blank defaults

function pluck(array $keys, array $source) {
  $defaults = array_fill_keys($keys, '');
  return array_intersect_key($source, $defaults) + $defaults;
}

$data = pluck(['username', 'email', 'password'], $_POST);
# => $data will contain values for the keys, or blanks if not found

enforce a type on all array elements

declare(strict_types=1);

$input = ['one', 'two', 'three'];
$all_strings = (function (string ...$args) {
  return $args;
})(...$input);
# => throws if an element is not a string

make a function only run once, and use cached result

function once(callable $fn) {
  $result = null;
  return function (...$args) use ($fn, &$result) {
    if ($result === null) {
      $result = $fn(...$args);
    }
    return $result;
  };
}

$create_resource = once(function (...$args) {
  return connect_to_expensive_resource(...$args);
});

$connection = $create_resource();

modify function behavior through decoration

function list_users(...$args) {
  return ['bob', 'alice', 'peter'];
}

function admins_only(callable $fn) {
  return function (...$args) use ($fn) {
    if ($role === 'admin') {
      return $fn(...$args);
    }
    throw new SomeException();
  };
}

$admins_list_users = admins_only('list_users');
$users = $admins_list_users();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment