Hi,
I am developing an api layer for my application. I have designed a structure and need some advice/feedback for it. You can find the basic implementation of the structure at the bottom.
Here are my requirements for the structure:
- Response from API commands may need to be formatted in different formats (JSON,XML,etc.)
- Some API commands may require authentication, some may not
- Every API command should be open to extension via plugins (Notification on events, filtering of input/output paramters, etc.)
With these requirements in mind I have applied Decorator pattern to my API layer. I am not sure if I have designed the structure right and need to be sure about it.
The last item in requirements list is not covered in the implementation below because I am still trying to figure out how to do that.
What do you think? Am I on the right path?
<?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();
?>