public function setLogger(\Psr\Log\LoggerInterface $logger) {
$this->logger = $logger;
}
protected function log($message) {
$this->logger->info($message);
}
}
在类中使用Trait
namespace User;
use Traits\Loggable;
use Psr\Log\LoggerInterface;
class Auth {
use Loggable;
public function __construct(LoggerInterface $logger) {
$this->setLogger($logger);
}
public function login($username, $password) {
$this->log("Attempting login for {$username}");
// 登录逻辑
}
}
3.2 设计模式的应用
(1)工厂模式
封装对象创建逻辑,便于替换实现。例如,数据库连接工厂:
interface DatabaseConnection {
public function connect();
}
class MySQLConnection implements DatabaseConnection {
public function connect() {
return new \PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
}
}
class DatabaseFactory {
public static function create($type) {
switch ($type) {
case 'mysql':
return new MySQLConnection();
default:
throw new \InvalidArgumentException("Unsupported database type");
}
}
}
(2)策略模式
定义一系列算法,封装每个算法并使它们可互换。例如,支付策略:
interface PaymentStrategy {
public function pay($amount);
}
class CreditCardPayment implements PaymentStrategy {
public function pay($amount) {
echo "aid {$amount} via Credit Card";
}
}
class PayPalPayment implements PaymentStrategy {
public function pay($amount) {
echo "aid {$amount} via PayPal";
}
}
class PaymentProcessor {
private $strategy;
public function __construct(PaymentStrategy $strategy) {
$this->strategy = $strategy;
}
public function executePayment($amount) {
$this->strategy->pay($amount);
}
}
四、实际项目中的模块化架构
以一个电商系统为例,展示如何划分模块: