Our way: Classes and Methods

robsontenorio

Robson Ten贸rio

Posted on October 19, 2023

Our way: Classes and Methods

馃憠 Go to Summary

There is no wrong or right way, there is our way.

-- Someone

.
.
.

Class attributes types

WTF!?

class Customer
{
    public $points;
    public $available;
}

Enter fullscreen mode Exit fullscreen mode

Nice!

class Customer
{
    public int $points;
    public bool $available;
}
Enter fullscreen mode Exit fullscreen mode

.
.
.

Constructor property promotion

WTF!?

class Customer
{
    public string $name;
    public string $email;
    public Date $birth_date;

    public function __construct(
        string $name, 
        string $email, 
        Date $birth_date
    ) {
        $this->name = $name;
        $this->email = $email;
        $this->birth_date = $birth_date;
    }
}
Enter fullscreen mode Exit fullscreen mode

Nice!

class Customer
{
    public function __construct(
        public string $name, 
        public string $email, 
        public Date $birth_date,
    ) { }
}

Enter fullscreen mode Exit fullscreen mode

.
.
.

Methods types

WTF!?

public function calculate($points, $available)
{
   ...

   return $score;
}

Enter fullscreen mode Exit fullscreen mode

Nice!

public function calculate(int $points, bool $available): float
{
   ...

   return $score;
}
Enter fullscreen mode Exit fullscreen mode

.
.
.

Fluent sintaxe

WTF!?

$mary = User::first();

$payment = new Payment(12.98, '2023-01-09', $mary, 4.76);
$payment->process();
Enter fullscreen mode Exit fullscreen mode

Nice!

$mary = User::first();

(new Payment)
   ->for($mary)
   ->amount(12.98)
   ->discount(4.78)
   ->due('2023-01-09')
   ->process();

Enter fullscreen mode Exit fullscreen mode

.
.
.

Encapsulate contexts

WTF!?


public function makeAvatar(string $gender, int $age, string $hairColor)
{
   ...   
   return 'https://...';
}

$user = User::first();

makeAvatar($user->gender, $user->age, $user->hairColor);
Enter fullscreen mode Exit fullscreen mode

Nice!

public function makeAvatarFor(User $user): string
{
   ...
   return 'https://...';
}

$user = User::first();

makeAvatarFor($user);
Enter fullscreen mode Exit fullscreen mode
馃挅 馃挭 馃檯 馃毄
robsontenorio
Robson Ten贸rio

Posted on October 19, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Our way: Classes and Methods
laravel Our way: Classes and Methods

October 19, 2023

Our way: Laravel Code Guidelines
laravel Our way: Laravel Code Guidelines

October 19, 2023

Our way: Tests
laravel Our way: Tests

October 19, 2023

Our way: Let the code breath
laravel Our way: Let the code breath

October 19, 2023