KO3:假装在kohana_orm模型上的属性
-
01-10-2019 - |
题
说我有一个非常简单的模型,看起来像这样:
class Model_Person extends ORM
{
/*
CREATE TABLE `persons` (
`id` INT PRIMARY KEY AUTO_INCREMENT,
`firstname` VARCHAR(45) NOT NULL,
`lastname` VARCHAR(45) NOT NULL,
`date_of_birth` DATE NOT NULL,
);
*/
}
有什么方法可以添加所有名称的假装属性?
例如,我可以这样做:
$person = ORM::factory('person', 7);
echo $person->fullname;
而不是这个:
$person = ORM::factory('person', 7);
echo $person->firstname.' '.$person->lastname;
另一个例子可能是 is_young
如果年龄低于一定数量,将计算人年龄并返回的财产。
解决方案
您可以使用“魔术” __get()
这样的方法:
public function __get($column)
{
switch($column)
{
case 'fullname' :
return $this->firstname.' '.$this->lastname;
case 'is_young' :
// calculate persons age
}
return parent::__get($column);
}
或者您可以创建其他方法 fullname()
和 age()
(对我来说似乎更好)。
其他提示
为什么不使用此解决方案?
class Model_Person extends ORM
{
public function fullname()
{
return $this->firstname.' '.$this->lastname;
}
}
$person = ORM::factory('person', 1);
echo $person->fullname();
您可以在以下 application/classes/ORM.php
(application/classes/orm.php
3.2之前的Kohana:
<?php
class ORM extends Kohana_ORM {
public function __get($name) {
$getter = 'get_' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
}
return parent::__get($name);
}
}
然后,您可以在模型类中添加一种方法:
public function get_fullname() {
return $this->firstname . ' ' . $this->lastname;
}
并能够作为属性访问它。
不隶属于 StackOverflow