我需要在我的用户实体中有一个虚拟属性。我遵循CakePHP的书。
UserEntity.php
namespace App'Model'Entity;
use Cake'ORM'Entity;
class User extends Entity {
protected $_virtual = ['full_name'];
protected function _getFullName() {
return $this->_properties['firstname'] . ' ' . $this->_properties['lastname'];
}
}
控制器
$users = TableRegistry::get('Users');
$user = $users->get(29);
$firstname = $user->firstname; // $firstname: "John"
$lastname = $user->lastname; // $lastname: "Doe"
$value = $user->full_name; // $value: null
我完全按照书上的方法做了,我只得到了一个null
的值。
根据@ndm,问题是由于错误的文件命名。我将用户实体类命名为UserEntity.php
。CakePHP的名称约定是:
实体类OptionValue可以在OptionValue.php文件中找到。
谢谢。
namespace App'Model'Entity;
use Cake'ORM'Entity;
class User extends Entity {
protected $_virtual = ['full_name'];
protected function _getFullName() {
return $this->firstname . ' ' . $this->lastname ;
}
}
你可以在这里返回资源
为什么不这样做呢?
/*
* Return Fullname
*/
public function getFullname()
{
$name = $this->firstname . ' ' . $this->lastname;
return $name;
}