Cakephp 3 的虚拟字段

Virtual fields with Cakephp 3

我需要在我的用户实体中有一个虚拟 属性。我关注了CakePHP book.

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 的说法,问题是由于错误的文件命名造成的。我将用户实体命名为 class UserEntity.phpThe CakePHP name conventions 表示:

The Entity class OptionValue would be found in a file named OptionValue.php.

谢谢。

为什么不做这样的事情呢?

/*
 * Return Fullname
 */
public function getFullname()
{
    $name = $this->firstname . ' ' . $this->lastname;
    return $name;
}
namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity {

protected $_virtual = ['full_name'];

 protected function _getFullName() {
   return $this->firstname . ' ' . $this->lastname ;
 }
} 

you can back to resource here