如何检索表属于模型的所有字段,并使用该模型的对象引用访问它们


How to retrieve all fields whose table belongs to a model and access them with object reference of that model?

我想在PHP中开发专有的MVC框架,并以清晰的方式理解OOP概念。我被困在这里了。首先看一下代码片段....

// main model class
class Model{
    protected static $table;
    protected static $primary_key;
    protected static $conn;
    public function __construct()
    {
        // variable calling from configuration file
        global $defalult_database_engine,$connections;
        self::dbConnection();
        // query to fetch all columns name belo
        $query="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA =? AND TABLE_NAME =?";
        $stmt=self::$conn->prepare($query);
        $stmt->execute(array($connections['mysql']['database'],'users'));
        $fields=$stmt->fetchAll(PDO::FETCH_OBJ);
        foreach($fields as $field)
        {
            $fileldname=$field->COLUMN_NAME;
            // creating variable name to matching to the tables fields name
            // how to set value of this variable via object
            $$fileldname;
        }
    }

子模型是这样的

class Users extends Model
{
    protected static $table='users';
}

现在转向控制器

class UserController extends Controller{
     public function __construct(){
     }
     public function createUser(){
        // user model
        $user=new Users();
        // calling attributes of the table and set their value
        $user->name='full name';
        $user->user_name='user name';
        $user->password='password';
        // finally save the value of fields
        $user->save();            
     }
}

我想以上述方式工作。我将表的字段名转换为变量,但无法通过其对象....引用它与上面给出的UserController完全相同。有什么办法使它成为可能吗?实际上,我目前正在使用Laravel 4.2,并受到影响;

无需从表中检索字段详细信息;而不是检索,我们必须利用动态实例变量;它可以在PHP中生成,如以下代码

$user->user_name; // $user_name variable has been created dynamically and bolongs to the $user table
$user->user_name='your user_name'; // value assigned to dynamic instance variable
$user->save();// this function is defined to the model class

和主模型的save()的代码应该如下所示:

public function save()
{
   $datainfo = (array)$this // this assing the array to the $datainfo variable with all dynamic instance variable
   // do your manipulation with data received in $datainfo
}  

我看到你在尝试重新创建Laravel的语法——听起来像一个有趣的项目。

Laravel使用PHP的__get()魔法方法来创建一个模型属性数组。

下面是Laravel __get和getAttribute方法的源代码:

public function __get($key)
{
    return $this->getAttribute($key);
}
public function getAttribute($key)
{
    if (array_key_exists($key, $this->attributes) || $this->hasGetMutator($key)) {
        return $this->getAttributeValue($key);
    }
    return $this->getRelationValue($key);
}