PHP. 8 trucos que te ayudarán a escribir código más limpio

Recopilación de algunos trucos que podemos usar en PHP para escribir mejor código

Image for post
Image for post
Photo by James Pond on Unsplash

1. Null coalescing operator

$someArray = ['one' => 'foo', 'two' => 'bar'];$one = isset($someArray['one'] ? $someArray['one'] : 'empty'; 
// 'foo'
$three = isset($someArray['three'] ? $someArray['three] : 'empty';
// 'empty'
$someArray = ['one' => 'foo', 'two' => 'bar'];$one = $someArray['one'] ?? 'empty'; 
// 'foo'
$three = $someArray['three] ?? 'empty';
// 'empty'

2. Invokable classes

class A {
public function __invoke() {
print_r('Hello world!);
}
}
$a = new A();
($a)(); // 'Hello World'
class B {
public function __invoke(int $a): int {
return $a * 2;
}
}
$b = new B();
($b)(5); // 10

3. Traits

// A.php<?php class A {  private $createdAt;  public function getCreatedAt(): \DateTimeInterface {
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self {
$this->createdAt = $createdAt;
return $this;
}
// getters and setters and rest of properties
}
// B.phpclass B { private $createdAt; public function getCreatedAt(): \DateTimeInterface {
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self {
$this->createdAt = $createdAt;
return $this;
}
// getters and setters and rest of properties
}
// Timestampable.phptrait Timestampable {  private $createdAt;  public function getCreatedAt(): \DateTimeInterface {
return $this->createdAt;
}
public function setCreatedAt(\DateTimeInterface $createdAt): self {
$this->createdAt = $createdAt;
return $this;
}
}// A.php<?phpclass A { use Timestampable; // getters and setters and rest of properties
}
// B.phpclass B { use Timestampable; // getters and setters and rest of properties
}
$a = new A();
$a->getCreatedAt();

4. array_map, array_filter, array_reduce

// imperative $myArray = [1, 2, 3]; 
$multipliedArray = [];
foreach ($myArray as $item) {
$multipliedArray[] = $item * 2;
}
// declarative$multipliedArray = array_map(
function(int $item) { return $item * 2; },
$myArray
);
// imperative$myArray = [1, 2, 3]; 
$filteredArray = [];
foreach ($myArray as $item) {
if ($item % 2 === 0) {
$filteredArray[] = $item;
}
}
// declarative$filteredArray = array_filter(
$myArray,
function(int $item) { return $item % 2 === 0; }
);
// imperative$myArray = [1, 2, 3]; 
$total = 0;
foreach ($myArray as $item) {
$total += $item;
}
// declarative$total = array_reduce(
$myArray,
function(int $ac, int $item) { return $ac + $item; },
0
);
Image for post
Image for post
Photo by Sasha Bond on Unsplash

5. Desestructurar arrays

$people = [
[1, 'Tom'],
[2, 'Fred'],
];

// Estilo de []
[$firstPerson, $secondPerson] = $people;
[$id, $name] = $firstPerson;
foreach ($people as [$id, $name]) {
// do something
}

6. Arrow functions

$numbers = [1, 2, 3];
$multipliedNumbers = array_map(fn($x) => $x * 2, $numbers);

7. Invocar métodos y funciones mediante variables

class A {
public function someMethod() {
echo 'hello world';
}
}
$a = new A();
$method = 'someMethod';
$a->$someMethod(); // hello world
class Invoker {
public function executeMethod($object, string $method) {
$object->$method();
}
}
class A {
public function doSomething() {
echo 'hello world';
}
}
$a = new A();
$invoker = new Invoker();
$invoker->executeMethod($a, 'doSomething');

8. Finally en try/catch

$file = fopen('log.txt', 'a');

try {
fwrite($file, 'Throwing exception..');
throw new \Exception();
} catch (\Exception $e) {
echo 'Threw a RangeException: ' . $e->getMessage();
} finally {
// Always make sure that we close the file

echo 'Reached the finally block';
fwrite($file, 'Reached the finally block');
fclose($file);
}

Conclusiones

¿Quieres recibir más artículos como este?

Written by

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store