我正在为我的应用程序开发api层。我设计了一个结构,需要一些建议/反馈。你可以在底部找到结构的基本实现。开发一个API层。需要关于Decorator模式使用的一些建议和反馈
这里是我的结构要求:(JSON,XML等)
- 从API命令的响应可能需要以不同的格式进行格式化
- 一些API命令可能需要进行身份验证,有的可能不
- 每个API命令应该是开放的,以通过插件扩展(通知关于事件,输入/输出paramters的滤波等)
考虑到这些要求我已将Decorator模式应用于我的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();
?>
现在我在想,也许我应该实施战略模式,而不是装饰模式。因为我想选择不同的输出格式策略,所以不要将输出格式策略层叠在一起。也许战略模式输出格式和装饰模式认证。天啊!? – matte 2010-10-15 10:31:45