bharanikumar Bs
bharanikumar Bs

Reputation: 183

cakePHP call a controller function from a ctp file

How do I call this function in a view (.ctp file)

The actual function is defined in the UserController class

 function verbose_log($msg) {
    date_default_timezone_set('Asia/Calcutta');
    $today = date("Ymd");
    $timestamp = time();
    $filename = "errorlog";
    if (!file_exists($filename)) { 
        echo "The file $filename exists";
        $ourFileHandle = touch($filename) or die("can't open file");    
    } 
    $fd = fopen($filename, "a");
    $str = "${today}|${timestamp}|${msg}";
    fwrite($fd, $str . PHP_EOL);
    $timestamp ='';
    fclose($fd); 
}

Upvotes: 1

Views: 4276

Answers (3)

Amar Banerjee
Amar Banerjee

Reputation: 5012

Using requestAction you can call a controller method in to your view page.

e.g.

$this->requestAction('/ControllerName/MethodName/');

Upvotes: 0

deizel.
deizel.

Reputation: 11232

As stated by others, you should call another controller method from your controller action:

class UsersController extends AppController {

    public function paymentresp() {
        // do stuff
        $this->_verbose_log($logMessage);
        // do more stuff
    }

    protected function _verbose_log($message) {
        // log stuff
    }
}

(By prefixing the method name with an underscore [the convention for protected methods], people won't be able to run this as a controller action by visiting http://example.com/controller/verbose_log)

Also, all CakePHP objects inherit a log method which calls CakeLog internally. You could use this existing functionality instead of implementing it yourself:

class UsersController extends AppController {

    public function paymentresp() {
        // do stuff
        $this->log($logMessage, 'error');
        // or
        CakeLog::write('error', $logMessage);
        // do more stuff
    }
}

Upvotes: 1

Benjam
Benjam

Reputation: 5326

Move your function to bootstrap.php, and you can run it from anywhere.

Upvotes: 0

Related Questions