用于crud操作的通用web服务


Yii 1.1 General purpose web service for crud operations

使用Yii 1.1,我考虑创建一个基于soap的web服务,该服务对模型执行常见的CRUD操作。例如,我只想为所有模型创建一个CreateObject函数,该函数接收一些参数,动态查找模型并将这些参数分配给适当的模型属性。例如,对于用户模型,我在web服务控制器中创建了以下操作:

 /** Create a new User record
 * @param string username
 * @param string password
 * @param string family
 * @param string name
 * @param string title
 * @param string email
 * @param string mobile
 * @return mixed true on success or an array of validation errors on failure
 * @soap
 */
public function createUser($username, $password, $family, $name="", $title="", $email="",$mobile="")
{
    $newUser = new User();
    $newUser->username = $username;
    $newUser->password = $password;
    $newUser->family = $family;
    $newUser->name = $name;
    $newUser->title = $title;
    $newUser->email = $email;
    $newUser->mobile = $mobile;
    //Get user roles
  /* if (is_array($roles) && !empty($roles)) {
        $roleList = User::getRoleList();
        $newUser->_roles = array_intersect($roles, $roleList);
    } else $newUser->_roles = array();*/
    if($newUser->save())
        return true;
    else
        return $newUser->getErrors();
}

这个函数通过web服务调用来创建一个新用户,它工作得很好。然而,我必须做同样的事情来从其余的模型中创建一个新对象。

我听说过实体模式实体工厂,这可能有助于我存档这个目标,但我没有找到任何好的教程。

在SOAP中使用接口或继承是相当棘手的,因此更简单的方法是修改SOAP web服务,使其接收两个字符串,一个用于模型名称,另一个用于模型属性的json字符串,因此您可以通过以下方式实例化模型:

public function create($model,$attributes){
  $model=new $modelName;
}

也可以使用php json函数来解码编码为json对象的属性。
如果您需要一些复杂的逻辑来初始化您的模型,您可以尝试使用工厂方法或工厂类。一个非常简单的例子可以是这样的:

class ModelsFactory{
  //use constants to identify the classes that you can return
  const Model1=1;
  const Model2=2;
  public static getInstance($model){
    $modelInstance=null;
    switch($model){
       case Model1:
       //... initialize a model1 class and asign to $modelInstance
       case Model2:
       //...
    }
    return $modelInstance;
  }  
}

可以看到,可以用一种简单的方式初始化复杂的类。你也可以根据你的需要扩展它。此外,如果你需要参数,只需将它们以对象或关联数组的形式添加到creator方法中。
希望这对你有帮助!