Hasan Setiawan

Write, write, write give your wings on code!

Follow me on GitHub

# 5 # S.O.L.I.D Object Oriented Design

In PHP OOP we already know about Dependency Injection, or some design pattern like Factory, singleton. And how about SOLID?

SOLID stands for

Single responsibility principle
Open closed principle
Liskov substitution principle
Interface segregation principle
Dependency inversion principle

# 5 # Dependency inversion principle

This principle states that high level modules should not depend on low level modules. High level modules should never change and should be decoupled (seperated) from low level modules that could be changed on a daily basis.

In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used from another interface. It is often used to make existing classes work with others without modifying their source code.

              
                // EmailTokenInformationProvider
                interface EmailTokenInformationProvider
                {
                    /**
                     * @param string $emailToken
                     * @return DateTimeImmutable
                     */
                    public function getCreationTime($emailToken);
                }


                // UserEmailTokenInformationProvider
                class UserEmailTokenInformationProvider implements EmailTokenInformationProvider
                {
                    private $userModel;

                    public function __construct(UserModel $userModel)
                    {
                      $this->userModel = $userModel;
                    }

                    public function getCreationTime($emailToken)
                    {
                      $userRow = $this->userModel->getByEmailToken($emailToken);

                      if (empty($userRow)) {
                          throw new EmailTokenNotFound($emailToken);
                      }

                      $emailTokenCreatedAt =
                          new DateTimeImmutable($userRow['email_token_created_at']);

                      return $emailTokenCreatedAt;
                    }
                }
              
          

How to correctly instantiate our EmailTokenService:

              
                  // App
                  $userModel = new UserModel();
                  $userEmailTokenInformationProvider = new UserEmailTokenInformationProvider($userModel);
                  $emailTokenService = new EmailTokenService($userEmailTokenInformationProvider);

                  $isEmailTokenValid = $emailTokenService->isEmailTokenValid($emailToken);