1

Prehistory:

I have Microsoft SQL Server as DBMS behind my Yii2 REST API. SQL Server has its internal data types: geography and geometry. Techincally, in terms of PDO, these types are PHP binary strings

Question:

So, i need a transparent way to map columns of these types to my class MyApp\Geometry, for example. That is i should be able to:

  1. access ActiveRecord instance property as Geometry instance(e.g $model->geometryBorders->someGeometryTransformation();
  2. save ActiveRecord instance with Geometry property transformation by __toString() method

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

So, are there any way to map ActiveRecord attribute to PHP class? I belive, that someone has already met this problem before.

1 Answer 1

1

You may use afterFind() method or afterFind event to userialize object from DB.

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

And reverse operation before saving (beforeSave() method or beforeInsert and beforeUpdate events):

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.