DEV Community

Cover image for Our way: Classes and Methods
Robson Tenório
Robson Tenório

Posted on • Updated on

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

Top comments (1)

Collapse
 
gurpreetkait profile image
Robin Dev • Edited

great !!