ZF2-rest-api编码风格(驼色大小写或下划线)


ZF2 rest api coding style (camel-case or underscore)

我正在为rest api中的mat编写以下代码。

我认为,在控制器和服务层中完成的验证负责编写业务逻辑,而模型负责数据库操作。我希望我是对的。

我在这里的澄清是,我可以将var_id(下划线分隔)发送到服务层,还是作为varID(驼色大小写)发送。

我搜索了很多api调用,其中大多数都是var_id,这也是我使用自己的原因。

但是我怎么能在这里使用这个变量呢,因为zend框架代码使用camel-case,如果我为每个变量分配变量varID = var_id,对吗。

$dataSendToService = array(
    $varID = var_id,
    $varID2 = var_id2;
);

我在create方法中调用api,如下所示。

http://128.12.788.88/api/v1/users/72

json-get方法,类似于

{
    "var_id":"var_value",
    "var_id1":"var_value1"
}

控制器内:

function create() {
    $body = $this->getRequest()->getContent();
    $data = json_decode($body); 
    $id  = $this->params('id');
    //validation
    if( !isset( $data->pat_id ) || empty( $data->pat_id ) ) {
        $resp = array(
            'status' => 'failure',
            'errorCode' => 531, 
            'errorMessage' => 'Patient ID should not be empty'
        );
        return new JsonModel($resp);
    }

    if( !isset( $data->doc_id ) || empty($data->doc_id )) {
        $resp = array(
            'status' => 'failure', 
            'errorCode' => 532, 
            'errorMessage' => 'Doctor ID should not be empty'
        );
        return new JsonModel($resp);
    }
    if( !isset( $data->apt_time ) || empty($data->apt_time )) {
        $resp = array(
            'status' => 'failure',
            'errorCode' => 533, 
            'errorMessage' => 'Appointment time should not be empty');
        return new JsonModel($resp);
    }
    if( !isset( $data->apt_subject ) || empty($data->apt_subject )) {
        $resp = array(
            'status' => 'failure', 
            'errorCode' => 534, 
            'errorMessage' => 'Appointment Subject time should not be empty');
        return new JsonModel($resp);
    }
    $sm = $this->getServiceLocator();
    $dbAdapter = $sm->get('Zend'Db'Adapter'Adapter');
    $usersService = new UsersService($dbAdapter);
    $resp = $usersService->profile($data,$id);
}

在役:

function create() {
    //get the data and pass it to model
}

型号:

function create() {
    //get the data and insert in table and return the result       
}

ZF2中使用下划线分隔的值是完全可以的,但实际上驼色大小写似乎更常见。

您绝对不必手动完成所有这些操作,您可以轻松地使用过滤器将json变量更改为驼色大小写:

use Zend'Filter'Word'CamelCaseToUnderscore;
...
$filter = new CamelCaseToUnderscore();
print $filter->filter('ThisIsMyContent');

返回下划线分隔:

use Zend'Filter'Word'CamelCaseToDash;
...    
filter = new CamelCaseToDash();
print $filter->filter('ThisIsMyContent');

如果您使用hydrator,那么您可以使用ZF2 ClassMethods hydrator,通过向构造函数传递布尔值,可以在两者之间设置为extracthydrate

underscore-separated(真)或camel-case(假)

use Zend'Stdlib'Hydrator'ClassMethods;
...
$boolean = true|false;
$hydrator = new ClassMethods($boolean)