如何从行为中的事件中获取表名

How to get tablename from Event in Behavior

我在 CakePHP 3.0.11 中编写一个行为,我可以 var_dump() 和 Log::debug() 我行为的 beforeSave() 方法中的 $event 对象,并且可以看到对象数据,但不能访问对象的属性。 我只是想从对象中获取 table(别名、类名、table 名称等)名称。
我想在我的行为中做这样的事情:

public function beforeSave(Event $event, Entity $entity)
{
    $table = $event->_alias;
    // etc.
}

我尝试了从事件中提取 table 对象的事件的 subject() 方法,

$table = $event->subject();

当我var_dump或调试返回的对象时,显示:

Debug: App\Model\Table\CompaniesTable Object
(
    [registryAlias] => Companies
    [table] => companies
    [alias] => Companies
    [entityClass] => App\Model\Entity\Company
    [associations] => Array
        (
            [0] => defaultshippingusers
    (...)
    [defaultConnection] => default
    [connectionName] => default
)

但我无法从我的 $table 对象访问 'table'、'alias' 等。 当我这样做时,出现致命错误:

Table Companies is not associated with 'alias'

有没有一种简单的方法可以从行为中的 $event 对象中获取 Table 名称?

转储对象不一定会给您对象结构的表示,而是通过 the magic __debugInfo() method 定义的自定义格式调试信息。

https://github.com/cakephp/cakephp/blob/3.0.11/src/ORM/Table.php#L2190

Table 类 没有 tablealias 属性,但具有相同名称的方法,看看 Cookbook 和 API 文档。

$alias = $event->subject()->alias();

您还可以直接从行为中获取 table 名称或别名,而无需使用 $event 对象:

$this->getTable()->table();
$this->getTable()->alias();

如果您将自己的函数添加到不传入 $event 的行为中,这将很有用。