cakephp 中的 requestAction

Max*_*rai 2 php cakephp

我已将 GeoIP 集成到我的 CakePHP 中。现在我必须从我的视图文件中调用它。我在我的控制器中做了这样的功能:

function getCountry($ip)
{
    $this->GeoIP->countryName($ip);
}
Run Code Online (Sandbox Code Playgroud)

GeoIP是一个包含的组件。

当我在全球视野中写下这样的内容时: $this->GeoIP->countryName('8.8.8.8')它运行良好,但是,据我记得,这对于 MCV 架构来说是错误的。所以正确的方法是调用requestAction我的控制器。

这里我有两个问题:我必须在位于视图文件中的 php 函数中执行此操作:

// MyView.php:
<?php
   function Foo()
   {
      $this->GeoIP->countryName(...);
   }
?>
Run Code Online (Sandbox Code Playgroud)

第一个错误是$this函数内部不可用,第二个错误是如何getCountry从我的组件调用并将需要的 ip 地址传递到$ip

我试过了:

echo $this->requestAction('Monitoring/getCountry/8.8.8.8');
Run Code Online (Sandbox Code Playgroud)

Monitoring是控制器名称。

但这没有返回任何错误。什么是正确的方法以及如何在函数中调用它?

Thi*_*lem 5

像这样的东西:

布局 -> View/Layouts/default.ctp (适用于任何其他视图/元素或块)

<h1>My Website</h1>
<?php echo $this->element('GeoIP') ?>
Run Code Online (Sandbox Code Playgroud)

Element -> View/Elements/GeoIP.ctp (使用一个元素,这样你就可以缓存它,而不是每次都请求控制器)

<?php
$country = $this->requestAction(array('controller' => 'Monitoring', 'action' => 'ipToCountry'));

echo "You're from {$country}?";
?>
Run Code Online (Sandbox Code Playgroud)

控制器 ->控制器/MonitoringController.php

public function ipToCountry() {
    // Only accessible via requestAction()
    if (empty($this->request->params['requested']))
        throw new ForbiddenException();

    return $this->GeoIP->countryName('8.8.8.8');
}
Run Code Online (Sandbox Code Playgroud)