php - Codeigniter 查询结果返回带有 setter 的自定义结果对象

标签 php codeigniter oop codeigniter-2

CI 客户对象到底是如何工作的?

根据 CI 文档,您还可以将字符串传递给 result(),它表示要为每个结果对象实例化的类(注意:必须加载此类)

$query = $this->db->query("SELECT * FROM users;");

foreach ($query->result('User') as $row)
{
   echo $row->name; // call attributes
   echo $row->reverse_name(); // or methods defined on the 'User' class
}
}

这是一个非常好的功能,但 Ci 所做的是它将返回一个 User 对象数组,并从行向其设置属性。

我有一个问题,我想在设置/获取之前更好地控制要公开访问的属性以及要修改的属性。

我怎样才能做到这一点?我可以告诉 CI 将所有属性传递给构造函数,以便该类可以填充自己的数据吗?

示例类用户

class User{
    private $data=array();
    protected $CI;
    //public $id,$name,$dob,$gender,$role,$username,$password,$salt,$picture,$lastactive;
    function __construct($data=null)
    {
        $this->data = $data; // i want to save data to a private var and allow attr. throu getters only
    }
    function set_password($p){
      $this->generateSalt();
      $this->data->password = $p.$this->data->salt;
    }
}

简而言之::

我想使用custom_result_object,但我不希望codeigniter为我填充类属性,相反,我希望类接收这些属性并以适当的方式自行填充它。

最佳答案

我在为自己寻找解决方案时发现了您的问题。

在深入研究文档后,我设法弄清楚了:

class user_item {
  // you can declare all the attributes you want as private
  private $id,$name,$dob,$gender,$role,$username,$password,$salt,$picture,$lastactive;

  function __construct(){
    // you can use the constructor to format data as needed
    $this->username = strtouppper($this->username);  
  }

  public function set_password($p){
    $this->generateSalt();
    $this->password = $p.$this->salt;
  }

  public function get_password(){
    return $this->password;
  }
}

设置完成后,您可以从 $this->db->result() 实例化此类

class User_model extends CI_Model {
   public function get_user($id){
     return $this->db->get_where('users', array('id' => $id), 1)->result('user_item');
   }
}

并根据需要调用类的任何公共(public)方法或属性

class Users extends CI_Controller {
  function __construct(){
     $this->load->model('user');
  }
  public function profile($user_id){
    var $myUser = $this->user->get_user($user_id);
    $myUser->set_password('myPassword');
    echo $myUser->get_password();
  }
}

我简化了代码以使其更清晰,但您明白了。

关于php - Codeigniter 查询结果返回带有 setter 的自定义结果对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26225943/

相关文章:

php - 创建用于根据时间获取动态数据的 API 端点

php - CodeIgniter——ACL 的最佳实现

c++ - 扩展类时的性能,组合与多态性

php - 在程序中使用 $_SESSION 的 Mysql 问题

php - 从 PHP 中的数组键创建新变量

php - Base64 编码图像

java - 如何为方法的所有错误或空参数设置默认值?

PHP正则表达式问题!

php - 如何在 Rest Server API 中获取/设置 header ?

C++构造函数参数问题