B
B
BonBon Slick2018-03-11 18:57:06
PHP
BonBon Slick, 2018-03-11 18:57:06

Private constructor or factory methods?

The question arose, is it necessary to give the opportunity to initialize the class constructor from anywhere?

public function __construct(
        Uuid $uuid
    ) {
        $this->uuid = $uuid;
    }

    public function createFromApi($newUserData)
    {
        UserFactory::fromApi($newUserData);
    }
    
    public function createFromAdminPanel($newUserData)
    {
        UserFactory::fromAminPanel($newUserData);
    }
    
    public function createFromImport($newUserData)
    {
        UserFactory::fromImport($newUserData);
    }

In factory methods, we create a class in such a way that it matches the business logic of the application in a particular situation.
Or leave the constructor public? But then the class can be initialized anywhere, and so new User () will be only and so much in a factory method of a certain type, depending on the creation conditions.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Korobkov, 2018-03-11
@BonBonSlick

whether it is necessary to give the chance to initialize the constructor of a class from everywhere?

Yes. The only exception is singleton .
public function createFromApi($newUserData)
public function createFromAdminPanel($newUserData)
public function createFromImport($newUserData)
This violates SOLID .
So, you have the wrong business logic and the wrong class structure.
A factory is just a helper that creates and sets some properties of an object. At the same time, no one bothers to change them later or do the same without a factory.
PS If the constructor is made private, then the factory (some third-party object) will not be able to create an object.
If you are going to put the factory inside the object itself, then this is shit code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question