KO3:模拟 Kohana_ORM 模型的属性
假设我有一个非常简单的模型,如下所示:
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
属性,该属性将计算人的年龄并在年龄低于某个数字时返回 true。
Say I have a very simple model that looks like this:
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,
);
*/
}
Is there a way I can I add sort of a pretend property with the full name?
So that I for example could do this:
$person = ORM::factory('person', 7);
echo $person->fullname;
instead of this:
$person = ORM::factory('person', 7);
echo $person->firstname.' '.$person->lastname;
Another example could be an is_young
property that would calculate the persons age and return true if the age was below a certain number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在
application/classes/ORM.php
中执行以下操作(
application/classes/orm.php
for Kohana 3.2 之前的版本):然后您只需向模型类添加一个方法即可:
并能够将其作为属性进行访问。
You can do the following in
application/classes/ORM.php
(
application/classes/orm.php
for Kohana prior to 3.2):Then you can just add a method to your model class:
And be able to access it as a property.
您可以使用“神奇”的
__get()
方法,如下所示:或者您可以创建其他方法,例如
fullname()
和age()
(似乎对我更好)。You can use "magic"
__get()
method like this:Or you can create additional methods like
fullname()
andage()
(seems better to me).为什么不使用这个解决方案呢?
Why not use this solution?