RMR架构 - 在何时加载表示和标题是有意义的?

时间:2011-10-22 16:25:27

标签: php

我目前正在开发开源RMR框架。目前,资源表示在资源本身中加载和解析,如下例所示(这是抽象级别,部分部分缩短以缩短此帖子):

/**
 * Processes a given request and returns a response. Makes use of a 
 * data source for data retrieval and an array of parameters 
 * (usually passed in from the route).
 * 
 * @param  Request  $request
 * @param  mixed    $dataSource
 * @param  array    $parameters
 * @return Response
 */
public function processRequest(Request $request, $dataSource, array $parameters)
{
    $method = strtolower($request->getMethod());
    $this->dataSource = $dataSource;
    $this->parameters = $parameters;
    $this->request = $request;

    if(method_exists($this, $method))
    {
        // Something like get, post, head in resources
        $data = $this->$method();
        $response = new Response(StatusCode::HTTP_OK);

        if(empty($data))
        {
            // Do some stuff, return 200 ok no message-body etc.
        }

        // Find preferred media type in request accept
        $mediaType = $request->getMediaType();

        // .. loop through find representation  ..
        // Representation is reponsible for adding its own headers and body to
        // response, does this make sense to you?
        $representation->parse($response, $data);

        return $response;
    }
    else
    {
        return new Response(StatusCode::HTTP_METHOD_NOT_ALLOWED);
    }
}

所以我的问题是,让资源处理加载自身的表示然后表示设置响应标题和正文是否有意义?

您的推荐方法是什么?

1 个答案:

答案 0 :(得分:3)

将其留给RepresentationResolver,对请求,响应和资源进行操作。保持班级小而清晰。

interface RepresentationResolver
{
    /**
     * @return Representation
     */
    public function resolve();
}

class DataRepresentationResolver implements RepresentationResolver
{
    public function __construct(your arguments)
    {

    }
    public function resolve()
    {
        ...
        $representation = $this->getRepresentation($this->data);
    }
}

然后在编译响应时:

$resolver = new DataRepresentationResolver(your arguments);
$representation = $resolver->resolve();
$representation->parse($response, $data);

然后,您可以对您认为合适的任何类型或RepresentationResolver进行编码,甚至可以对此类家庭进行编码,例如:使用特定请求类型或您指定的特定媒体类型(例如,通过mime-type)。