php - cakephp 中的 requestAction

标签 php cakephp

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

function getCountry($ip)
{
    $this->GeoIP->countryName($ip);
}

GeoIP 是一个包含的组件。

当我在全局 View 中写下这样的内容时: $this->GeoIP->countryName('8.8.8.8') 它运行良好,但我记得,这对于 MCV 架构是错误的。所以正确的方法是为我的 Controller 调用 requestAction

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

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

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

我试过:

echo $this->requestAction('Monitoring/getCountry/8.8.8.8');

Monitoring 是 Controller 名称。

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

最佳答案

像这样:

Layout -> View/Layouts/default.ctp (适用于任何其他 View /元素或 block )

<h1>My Website</h1>
<?php echo $this->element('GeoIP') ?>

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

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

echo "You're from {$country}?";
?>

Controller -> Controller/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');
}

关于php - cakephp 中的 requestAction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241197/

相关文章:

php - 在 View laravel 5 中包含 Controller

php - SQLSTATE[HY000] : General error: 1210 Incorrect arguments to mysqld_stmt_execute

php - 无法在任何其他文件中使用 php

php - 使用内连接选择 id

php - json_encode 序列化空字节

mysql - CakePHP 查找 - 按字符串到整数排序?

CakePHP 3 : Nested SQL functions in a query

javascript - 在cakePHP 2.*中动态添加验证规则

php - Cakephp 身份验证在 Internet Explorer 8 和 Chrome 中不起作用

php - CakePHP:无法访问 MySQL 数据库