Max Frai
Max Frai

Reputation: 64276

requestAction in cakephp

I've integrated GeoIP into my CakePHP. Now I have to call it from my view-file. I made in my controller such function:

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

GeoIP is a included component.

When I wrote in my view globally something like this: $this->GeoIP->countryName('8.8.8.8') it works well, but, as I remember, this is wrong for MCV architecture. So the right way is to call requestAction for my controller.

Here I have 2 problems: I have to do this in php function which is located in view-file:

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

First mistake is that $this isn't available inside the function, the second one is how to call getCountry from my component and pass need ip address into $ip?

I've tried:

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

Monitoring is a controller name.

But this returns nothing without any errors. What's the right way and how to call this in function?

Upvotes: 2

Views: 10625

Answers (2)

Lucian Vasile
Lucian Vasile

Reputation: 502

One of the basic principles in MVC is that you must not use logic in your view files (except some conditions). In your controller you must set the value in the view and use it there.

I you absolutely need to call your method after all the logic in the controller, you can use the beforeRender() method in your controller and it will be called right before rendering. You can set your value from there.

I don't see why you'd like to call a controller function in the view, unless you have business logic in there. That should be moved in the controller.

Hope I helped!

Upvotes: 3

Thiago Belem
Thiago Belem

Reputation: 7832

Something like this:

Layout -> View/Layouts/default.ctp (works on any other view/element or block)

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

Element -> View/Elements/GeoIP.ctp (use an element so you can cache it and don't request the controller every time)

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

Upvotes: 5

Related Questions