Sobes.tech
Junior — Middle

How would you apply the 'factory' pattern in your project?

sobes.tech AI

Answer from AI

The 'factory' pattern is used to create objects without explicitly specifying the class of the object being created. In PHP, this is convenient when you need to create objects of different classes but want to use them through a common interface.

Example of usage:

interface Logger {
    public function log(string $message);
}

class FileLogger implements Logger {
    public function log(string $message) {
        // Write to file
    }
}

class DatabaseLogger implements Logger {
    public function log(string $message) {
        // Write to database
    }
}

class LoggerFactory {
    public static function create(string $type): Logger {
        if ($type === 'file') {
            return new FileLogger();
        } elseif ($type === 'database') {
            return new DatabaseLogger();
        }
        throw new Exception('Unknown logger type');
    }
}

// Usage:
$logger = LoggerFactory::create('file');
$logger->log('Message');

This approach simplifies the extension and maintenance of the code, allowing the type of created objects to be changed without modifying client code.