T
T
topuserman2020-07-13 11:56:43
PHP
topuserman, 2020-07-13 11:56:43

Is this an exceptional situation?

For example, there is a class that in the constructor receives some input that is needed to initialize the object.

For example:

class User {
    private ?array $userData;

    public function __construct(int $userId) {
        $this->userData = ...;
        // ...
    }

    // ...

    public function getId(): int {
        return $this->userData["ID"];
    }

    public function getFullName(): string {
        return implode( " ",
            clearArray( [
                    $this->userData["NAME1"],
                    $this->userData["NAME2"],
                    $this->userData["NAME3"]
            ] )
        );
    }

    public function getLogin(): string {
        return $this->userData["LOGIN"];
    }

    public function getEmail(): string {
        return $this->userData["EMAIL"];
    }
}


What to do in cases when it is impossible to initialize an object according to the input data? For example, the given Id could not find the user ? Throw an exception? or create additional method isExist(): bool ?

I am inclined to the first option, because. in the second case, it will be necessary, each time, before using the class methods, to write a check if($user->isExist()) ..

How is it customary to solve such problems?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-07-13
@topuserman

Specific parameters must be passed to the entity : $id, $login, and not an array $userDatafrom which you need to extract this data, check their type and existence. With this approach, you can use typing and be confident in the data passed.
You can also create an entity with different factory methods .
The exception must be in your repository 's get() method . And don't confuse find() and get() methods :

  • find() - returns an entity or null .
  • get() - returns an entity or an exception .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question