问题
For CakePHP 2.3.8
How can I call Another Controller function in CronController.php
Any ideas?
回答1:
Below is the code:
App::import('Controller', 'Products'); // mention at top
// Instantiation // mention within cron function
$Products = new ProductsController;
// Call a method from
$Products->ControllerFunction();
Hope it helps some one !
回答2:
Use the $this->requestAction();
method in your controller action. It's not the most recommended pattern, but it can be useful and can return data or render a view based on your parameters.
回答3:
I referenced the manual to find a solution to this.
public function that_controller_function_you_are_writing () {
# this is cakes way of running required
App::import('Controller', 'Users');
$UsersController = new UsersController;
# now you can reference your controller like any other PHP class
$UsersController->that_function_you_needed();
}
This is the link: http://book.cakephp.org/2.0/en/core-utility-libraries/app.html
回答4:
The App::import('Controller', 'XXX');
did not work for me.
I'm using Cake 3.0
After a while I made it work
Function of the controller you want to call:
public function validateSomething($var = null)
{
return ...
}
In a different controller, where you need to call the previous function to validate something:
public function index()
{
// load the model you need depending on the controller you need to use
$this->loadModel('User');
// use this in case you have tu instantiate a new entity
$user = $this->User->newEntity();
$user = $this->User->patchEntity($user, $this->request->data);
// using the controller on the fly, you could assign it to a var
// call the function you need
$result = (new UserController())->validateSomething($user);
// Test if result has something:
$this->Flash->success(__($result));
}
回答5:
try this
<?php echo $this->Html->link( "Logout,".$user["username"], array('controller'=>'Users' ,'action'=>'logout') );?>
来源:https://stackoverflow.com/questions/19344988/cakephp-2-3-8-calling-another-controller-function-in-croncontroller-php