由于对你所链接的问题的解释非常广泛,我不会再为你重新定义它。相反,我将尝试通过注射示例向您展示。
class Logger {
private $__logger;
public function __construct($logger) {
$class = $logger . "Logger";
$this->$__logger = new $class();
}
public function write($message) {
$this->$__logger->write($message);
}
}
因此,在上面,您有一个类,您可以使用它来记录某处的信息。我们并不真正关心它是如何做到的,我们只是知道它确实如此。Logger
现在,我们有几种不同的日志记录可能性...
class DBLogger {
public function write($message) {
// Connect to the database and
// INSERT $message
}
}
class FileLogger {
public function write($message) {
// open a file and
// fwrite $message
}
}
class EMailLogger {
public function write($message) {
// open an smtp connection and
// send $message
}
}
现在,当我们使用记录器时,我们通过执行以下任一操作来执行此操作:
$logger = new Logger("DB");
$logger = new Logger("EMail");
$logger = new Logger("File");
我们总是以相同的方式与之交互(即我们称之为)。包装器实例包装实际的日志记录类,并代表我们调用其方法。$logger
write($message)
Logger
上述类型代码的更常见用法是使用配置文件来确定记录器是什么。例如,考虑您希望将日志记录发送到文件的情况。您可能有一个如下所示的配置:
$logging = array(
'type' => 'file',
'types' => array(
'file' => array(
'path' => '/var/log'
'name' => 'app_errors.log'
),
'email' => array(
'to' => 'webmaster@domain.com',
'from' => 'error_logger@domain.com',
'subject' => 'Major fail sauce'
),
'db' => array(
'table' => 'errors',
'field' => 'error_message'
)
)
);
您改编的课程可能如下所示:
class FileLogger {
public function __construct() {
// we assume the following line returns the config above.
$this->config = Config::get_config("logger");
}
public function write($message) {
$fh = fopen($this->config->path . '/' . $this->config->file);
fwrite($fh, $message . "\n");
fclose($fh);
}
}
我们将对其他类执行相同的操作。然后,通过对主包装器进行一些修改,我们可以使用配置数据创建正确的包装实例,并将其基于配置中定义的实例。一旦你有了类似的东西,切换到通过电子邮件登录就像在配置中更改一样简单。adapted
Logger
type
type