Fatal error: Call to a member function schemaCollection() on a non-object in ...vendor/cakephp/cakephp/src/ORM/Table.php on line 421

Fatal error: Call to a member function schemaCollection() on a non-object in ...vendor/cakephp/cakephp/src/ORM/Table.php on line 421

大家好,复活节快乐!

我在将遗留应用程序从 CakePHP 2.x 迁移到 CakePHP 3.x

时遇到了这个问题

我正在尝试在模型的初始化函数中加载数据库 table 的所有内容(ConfigurationsTable.php - 制作成单例)class。我也在构造函数中尝试了相同的代码,但仍然得到相同的错误。也试过将它移到一个单独的函数,但仍然没有成功。

它在 CakePHP 中工作正常 2.x 但我在 CakePHP 3 中遇到致命错误。

代码如下

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class ConfigurationsTable extends Table
{

private $_configurations;

public static function getInstance()
{
    static $instance = null;

    if ($instance === null) {
        $instance = new static();
    }

    return $instance;
}

public function is_set($key)
{
    return isset($this->_configurations->{$key});
}

public function fetch($key)
{
    return $this->_configurations->{$key};
}

public function initialize(array $config)
{
    $this->addBehavior('Timestamp');

    $this->_configurations = new \stdClass();

    $configs = $this->find('all');

    foreach ($configs as $c) {
        if (isset($c->key) && $c->key != '') {
            $this->_configurations->{$c->key} = $c->value;
        }
    }


}


public function validationDefault(Validator $validator)
{
    $validator
        ->notEmpty('key')
        ->add('key', [
            'unique' => [
                'rule' => 'validateUnique',
                'provider' => 'table',
                'message' => __('This configuration key already exists')
            ]
        ])
        ->notEmpty('value')
        ;

    return $validator;
}

导致错误的行是:$configs = $this->find('all');

任何人都可以为此提供解决方案吗? 我工作需要它..

非常感谢

您不能盲目应用 2.x 概念并期望它有效。在开始使用您不了解的代码之前,请至少看一下 API 文档

http://api.cakephp.org/3.0/class-Cake.ORM.Table.html#___construct

查看源代码本身以了解代码的实际作用会更好。

当手动实例化 table 类 时,您必须至少提供一个 connection instance. However, what you are doing there doesn't make much sense, there's not really a need for a custom static instance getter, that's what TableRegistry::get() 是为了。