调用布尔成员函数是什么意思以及如何修复

2021-12-21 00:00:00 php cakephp-3.0 model-view-controller

我是 cakePHP 3 的新手.我创建了一个控制器和模型,我在其中调用了一个函数来从数据库中获取所有用户.但是当我运行下面的代码时,我会得到以下错误在布尔值上调用成员函数 get_all_users()".

I'm new with cakePHP 3. I have created a controller and model where I call a function to get all users from the database. But when I run the code below I will get the following error "Call to a member function get_all_users() on boolean".

这个错误是什么意思,我该如何解决?

what does this error means and how can I fix this up?

User.php(模型)

namespace AppModelEntity;
use CakeORMEntity;

class User extends Entity {

    public function get_all_users() {
        // find users and return to controller
        return $this->User->find('all');
    }
}

UsersController.php(控制器)

namespace AppController;
use AppControllerAppController;

class UsersController extends AppController {

    public function index() {
        // get all users from model
        $this->set('users', $this->User->get_all_users());
    }
}

推荐答案

通常在使用控制器的不存在的属性时会发生此错误.

Generally this error happens when a non-existent property of a controller is being used.

与控制器名称匹配的表不需要是手动加载/设置为属性,但即使它们最初不存在,尝试访问它们会导致调用控制器魔术getter方法,该方法用于延迟加载表类属于控制器,它在出错时返回 false,这就是它发生的地方,你将调用一个布尔值的方法.

Tables that do match the controller name do not need to be loaded/set to a property manually, but not even they exist initially, trying to access them causes the controllers magic getter method to be invoked, wich is used for lazy loading the table class that belongs to the controller, and it returns false on error, and that's where it happens, you will be calling a method on a boolean.

https://github.com/cakephp/.../blob/3.0.10/src/Controller/Controller.php#L339

在您的情况下,问题是 User(单数,对于实体)与预期的 Users(复数,对于表)不匹配,因此没有匹配的表类可以找到.

In your case the problem is that User (singular, for entities) doesn't match the expected Users (plural, for tables), hence no matching table class can be found.

你的自定义方法应该放在一个表类中,UsersTable 类,然后你应该通过

Your custom method should go in a table class instead, the UsersTable class, which you should then access via

$this->Users

您可能想重新阅读文档,实体不查询数据(除非您例如实施延迟加载),它们代表一个数据集!

You may want to reread the docs, entities do not query data (unless you are for example implementing lazy loading), they represent a dataset!

相关文章