简体   繁体   English

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

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

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

I know this question is pretty old, but the proper solution here would be:我知道这个问题已经很老了,但这里的正确解决方案是:

$this->params['controller']

For more information on the 'params' attribute:有关“params”属性的更多信息:
http://book.cakephp.org/view/963/The-Parameters-Attribute-params http://book.cakephp.org/view/963/The-Parameters-Attribute-params

Try this.试试这个。 if u only need the name of the controller.如果您只需要控制器的名称。

Inflector::pluralize($this->name);
$GLOBALS['Dispatcher']->params['controller']

会给你控制器名称

I found a solution, it's not pretty but worked for me.我找到了一个解决方案,它不漂亮但对我有用。 I just use the $_REQUEST['url'] and catch de controller name by url.我只是使用 $_REQUEST['url'] 并通过 url 捕获控制器名称。 The downside of this solution, is that if you have a route different for default, this solution will not work... anyone have a better approach ?这个解决方案的缺点是,如果你有一条不同的默认路线,这个解决方案将不起作用......有人有更好的方法吗?

对于任何重新访问此问题并使用 CakePHP 3.x 的人:

$this->request->getParam('controller')

One of PHP's Magic Constants is __CLASS__ which will return the class name of the object it is within. PHP 的魔术常量之一是__CLASS__ ,它将返回它所在对象的类名。 This may get you what you need.这可能会为您提供所需的东西。

http://php.net/manual/en/language.constants.predefined.php http://php.net/manual/en/language.constants.predefined.php

Magic Constants and Methods are fun.魔术常量和方法很有趣。

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

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