【发布时间】:2011-04-25 20:37:14
【问题描述】:
我正在为我的应用程序开发一个 api 层。我设计了一个结构,需要一些建议/反馈。您可以在底部找到该结构的基本实现。
这是我对结构的要求:
- 来自 API 命令的响应可能需要采用不同格式(JSON、XML 等)
- 有些 API 命令可能需要身份验证,有些可能不需要
- 每个 API 命令都应通过插件对扩展开放(事件通知、输入/输出参数过滤等)
考虑到这些要求,我将装饰器模式应用于我的 API 层。我不确定我是否设计了正确的结构并且需要确定它。
需求列表中的最后一项没有包含在下面的实现中,因为我仍在尝试弄清楚如何做到这一点。
你怎么看?我走对了吗?
<?php
// Interfaces
interface I_API_Command {}
// Abstract classes
abstract class A_API_Command implements I_API_Command
{
abstract public function run();
}
abstract class A_Decorator_API_Command implements I_API_Command
{
protected $_apiCommand;
public function __construct(I_API_Command $apiCommand) {
$this->_apiCommand = $apiCommand;
}
abstract public function run();
}
// Api command class
class APIC_Tasks_Get extends A_API_Command
{
public function run() {
// Returns tasks
}
}
// Api command decorator classes
class APICD_Auth extends A_Decorator_API_Command
{
public function run() {
// Check authentication
// If not authenticated: return error
// If authenticated:
return $this->_apiCommand->run()
}
}
class APICD_JSON_Formatter extends A_Decorator_API_Command
{
public function run() {
return json_encode($this->_apiCommand->run());
}
}
// Usage
$apiCommand = new APICD_JSON_Formatter(new APICD_Auth(new APIC_Tasks_Get()));
$apiCommand->run();
?>
【问题讨论】:
-
现在我在想也许我应该实现策略模式而不是装饰器模式。因为我想选择一种不同的输出格式策略,而不是一层一层的输出格式策略。也许是用于输出格式的策略模式和用于身份验证的装饰器模式。天哪!?
标签: php oop design-patterns decorator