简体   繁体   English

CakePHP:在控制器中获取当前模型名称

[英]CakePHP: get current model name in a controller

I'm creating a behaviour that needs to log the current model name.我正在创建一个需要记录当前模型名称的行为。 How can I get the current model name from within a controller in CakePHP?如何从 CakePHP 的控制器中获取当前模型名称?

Your architecture is flawed when you want to get a controllers primary model name from a behavior.当您想从行为中获取控制器主要模型名称时,您的架构存在缺陷。 That's a violation of the MVC pattern.这违反了 MVC 模式。 Your app should have fat models and skinny controllers.你的应用应该有胖模型和瘦控制器。

Your Behavior already has the model instance as it is required to be passed to behaviors.您的行为已经具有模型实例,因为它需要传递给行为。 You can get the name from the model object:您可以从模型对象中获取名称:

// Cake 2.x
$Model->name
// Cake 3.x
$Table->name()

or it's alias或者它的别名

// Cake 2.x
$Model->alias
// Cake 3.x
$Table->alias()

The earlier example don't work, but it's work for me:前面的例子不起作用,但它对我有用:

// Cake 3.x    
$object->repository()->alias()

从 Cakephp 3 开始,你就可以使用

$this->modelClass

For cake 3.4 + and 4.x (CakePHP is on 4.2 at the time of writing this) you can use the following:对于 cake 3.4 + 和 4.x(在撰写本文时,CakePHP 为 4.2),您可以使用以下内容:

// For table
$Table->getTable();

// For alias    
$Table->getAlias();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM