Skip to content

Instantly share code, notes, and snippets.

View young-steveo's full-sized avatar
🦑
Workin'

Stephen Young young-steveo

🦑
Workin'
View GitHub Profile
@young-steveo
young-steveo / search.php
Last active June 20, 2018 17:38
Bad Example
<?php
if (empty($data["username"])) {
throw new \Exception("Username is required.");
}
if (empty($data["name"])) {
$first = $data["first_name"] ?? '';
$last = $data["last_name"] ?? '';
$data["name"] = "$first $last";
}
$params = new SearchParams($data['username'], $data['name']);
@young-steveo
young-steveo / SearchParams.php
Last active June 20, 2018 17:39
SearchParams Refactored
<?php
final class SearchParams {
private $username;
private $name;
private function __construct(string $username, string $name) {
$this->username = $username;
$this->name = $name;
}
public static function fromArray(array $params) : SearchParams {
if (empty($params["username"])) {
@young-steveo
young-steveo / apo-search-refactored.php
Last active June 20, 2018 17:39
Array Oriented Programming Refactored
<?php
final class User extends Requester {
public function search(SearchParams $params) : array {
return $this->request($params->toArray())->toArray();
}
}
@young-steveo
young-steveo / example2.php
Last active June 20, 2018 19:21
Array Oriented Programming - Bad Example
<?php
final class Payment {
public function subscribe(array $transaction) : array {
// 1
$transaction = [
'payment_method' => $transaction['payment_method'] ?? 'credit-card',
'amount' => $transaction['total'] ?? $transaction['subtotal'] ?? 0.0,
'currency' => $transaction['currency_code'] ?? 'USD'
] + $transaction;
$model = new TransactionModel();
@young-steveo
young-steveo / example2-refined.php
Last active June 20, 2018 19:24
Array Oriented Programming - Refined Transaction
<?php
final class Payment {
public function subscribe(PostParams $data) : Transaction {
$transaction = Transaction::fromPost($data);
$model = new TransactionModel();
$model->create($transaction);
$processor = $model->getProcessor($transaction); // a Processor object