Please suggest Yii preferred way to handle this problem.
I have an CActiveRecord model and it has a description attribute pulled from DB. I want to apply some filters on this attribute before returning it’s value.
I tried following but doesn’t seem to work.
public function getDescription() {
return stripslashes( $this->description );
}
This code is part of RESTful API so I need this to be in model.
If you absolutely need to have the method in the model, you should provide a different name for it. Perhaps something like getRestDescription() would be appropriate.
There’s not really enough information in your post to offer further guidance. I don’t think it’s a good idea to override the accessor method though, because you may need to display the description in other contexts.
Please let me know what more information you need from me. I tried to keep the problem statement simple as possible.
Accessor method with a different name works but I certainly need to pass it through a filter to remove back slashes.
You said its not a good idea to override accessor method but in my observation we actually cannot do it. Because my code sample doesn’t give expected result.
I also recommend a different getter to maintain consistency. If not, you’ll eventually run into “problems”.
Here is another example - I have devices with serial numbers that are have a "complex" internal representation, which have to be represented to the user in a simple way.
There is also a setter which sets the database field based on the user’s entry.
Both the setter and the getter call other functions not shown here that modify the internal representation to a user friendly representation and vice-versa. I’ve removed comments from the code for length and privacy.
private $_textualIdentifier;
public function setTextualIdentifier($value){
if($this->getScenario()!=='search') {
$this->device_identifier=$this->convertToInternalIdentifier($value, $this->device_type_id);
$this->_textualIdentifier=$value;
} else {
$this->_textualIdentifier=$value;
}
}
public function getTextualIdentifier(){
if($this->getScenario()!=='search') {
return self::convertToTextualIdentifier($this->device_identifier,$this->device_type_id);
} else {
return $this->_textualIdentifier;
}
}
Thank you all for providing your solutions and opinion.
I have implemented a different getter and called it manually where need. I needed to change some existing code. Well, it was only one time effort so nothing hard.