Zend Action Controller - 重构策略

Hor*_*Kol 6 php model-view-controller refactoring zend-framework

我已经在Zend Framework(1.10)上构建了一个首次运行的Web服务,现在我正在研究如何重构我的Action Controllers中的一些逻辑,这样我和我的团队的其他人就会更容易扩展和维护服务.

我可以看到哪里有重构的机会,但我不清楚最佳策略如何.控制器上最好的文档和教程只讨论小规模应用程序,并没有真正讨论如何抽象出更大规模的重复代码.

我们的动作控制器的基本结构是:

  1. 从请求正文中提取XML消息 - 这包括针对特定于操作的relaxNG架构进行验证
  2. 准备XML响应
  3. 验证请求消息中的数据(无效数据会引发异常 - 将消息添加到立即发送的响应中)
  4. 执行数据库操作(选择/插入/更新/删除)
  5. 使用所需信息返回操作的成功或失败

一个简单的例子就是这个动作,它根据一组灵活的标准返回供应商列表:

class Api_VendorController extends Lib_Controller_Action
{  
    public function getDetailsAction()
    {
        try {
            $request = new Lib_XML_Request('1.0');
            $request->load($this->getRequest()->getRawBody(), dirname(__FILE__) . '/../resources/xml/relaxng/vendor/getDetails.xml');
        } catch (Lib_XML_Request_Exception $e) {
            // Log exception, if logger available
            if ($log = $this->getLog()) {
                $log->warn('API/Vendor/getDetails: Error validating incoming request message', $e);
            }

            // Elevate as general error
            throw new Zend_Controller_Action_Exception($e->getMessage(), 400);
        }

        $response = new Lib_XML_Response('API/vendor/getDetails');

        try {
            $criteria = array();
            $fields = $request->getElementsByTagName('field');
            for ($i = 0; $i < $fields->length; $i++) {
                $name = trim($fields->item($i)->attributes->getNamedItem('name')->nodeValue);
                if (!isset($criteria[$name])) {
                    $criteria[$name] = array();
                }
                $criteria[$name][] = trim($fields->item($i)->childNodes->item(0)->nodeValue);
            }

            $vendors = $this->_mappers['vendor']->find($criteria);
            if (count($vendors) < 1) {
                throw new Api_VendorController_Exception('Could not find any vendors matching your criteria');
            }

            $response->append('success');
            foreach ($vendors as $vendor) {
                $v = $vendor->toArray();
                $response->append('vendor', $v);
            }

        } catch (Api_VendorController_Exception $e) {
            // Send failure message
            $error = $response->append('error');
            $response->appendChild($error, 'message', $e->getMessage());

            // Log exception, if logger available
            if ($log = $this->getLog()) {
                $log->warn('API/Account/GetDetails: ' . $e->getMessage(), $e);
            }
        }

        echo $response->save();
    }
}
Run Code Online (Sandbox Code Playgroud)

那么 - 知道我的控制器中的共性在哪里,什么是重构的最佳策略,同时保持Zend-like并且还可以使用PHPUnit进行测试?

我确实考虑过将更多的控制器逻辑抽象为父类(Lib_Controller_Action),但这使得单元测试变得更加复杂,这种方式在我看来是错误的.

Dav*_*aub 1

两个想法(只是根据上面的评论创建答案):

  1. 将通用性推入服务/存储库类?这些类将是可测试的,可跨控制器使用,并且可以使控制器代码更加紧凑。

  2. 将共性收集到行动助手中。