简体   繁体   English

将 ActiveRecord 属性映射到 Yii2 中的 PHP 类

[英]Mapping ActiveRecord attribute to PHP class in Yii2

Prehistory:史前:

I have Microsoft SQL Server as DBMS behind my Yii2 REST API.我的 Yii2 REST API 后面有 Microsoft SQL Server 作为 DBMS。 SQL Server has its internal data types: geography and geometry . SQL Server 有其内部数据类型: geographygeometry Techincally, in terms of PDO, these types are PHP binary strings从技术上讲,在 PDO 方面,这些类型是 PHP 二进制字符串

Question:题:

So, i need a transparent way to map columns of these types to my class MyApp\\Geometry , for example.因此,例如,我需要一种透明的方式将这些类型的列映射到我的类MyApp\\Geometry That is i should be able to:那就是我应该能够:

  1. access ActiveRecord instance property as Geometry instance(eg $model->geometryBorders->someGeometryTransformation();访问 ActiveRecord 实例属性作为Geometry实例(例如$model->geometryBorders->someGeometryTransformation();
  2. save ActiveRecord instance with Geometry property transformation by __toString() method通过__toString()方法保存带有Geometry属性转换的 ActiveRecord 实例

As of the second point - it looks clear for me ( as far, as i understand, PDO engine automatically converts all values to PHP string type before sending them to DBMS), but about the first point - i do not know how to implement it within the Yii2 architecture至于第二点 - 我看起来很清楚(据我所知,PDO 引擎会在将所有值发送到 DBMS 之前自动将它们转换为 PHP 字符串类型),但关于第一点 - 我不知道如何实现它在 Yii2 架构内

So, are there any way to map ActiveRecord attribute to PHP class?那么,有没有办法将 ActiveRecord 属性映射到 PHP 类? I belive, that someone has already met this problem before.我相信,之前有人已经遇到过这个问题。

You may use afterFind() method or afterFind event to userialize object from DB.您可以使用afterFind()方法或afterFind事件来用户化数据库中的对象。

public function afterFind() {
    parent::afterFind();
    $this->geometryBordersObject = Geometry::fromString($this->geometryBorders);
}

And reverse operation before saving ( beforeSave() method or beforeInsert and beforeUpdate events):保存前的反向操作( beforeSave()方法或beforeInsertbeforeUpdate事件):

public function beforeSave() {
    $this->geometryBorders = $this->geometryBordersObject->toString();

    return parent::beforeSave();
}

You may also try using getters and setters to provide virtual attributes, but it may be tricky with object.您也可以尝试使用 getter 和 setter 来提供虚拟属性,但使用 object 可能会很棘手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM