First, let’s have doubts.
Is there a way to execute a Controller function from another Controller with CI? And if there is, does it hurt the MVC in which it is worked? Or is there a better way to treat this situation?
It exists. I believe that for this problem there are several solutions and that depending on the case, some become more viable than the others. However, I will mention here only the solutions that I know and that do not hurt the MVC standard.
Inheritance
One of the ways to solve the problem is through Inheritance.
This requires the creation of a Controller Core that will be inherited by the others Controllers of your application (X and Y in the case) and within it you can implement the logic that the CRON is running.
For example:
./application/core/My_controller.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected function _rotina()
{
// Lógica
}
}
./application/controllers/Controller_x.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Controller_x extends MY_Controller {
// Action executada pelo CRON
public function action()
{
// Executa a rotina...
$this->_rotina();
}
}
./application/controllers/Controller_y.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Controller_y extends MY_Controller {
// Action executada pelo outro Controller
public function action()
{
// Executa a rotina...
$this->_rotina();
}
}
Helpers
Another way to solve the problem in Codeigniter is using Helpers.
To this end, a Helper customized in your application.
For example:
./application/helpers/rotina_helper.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if ( ! function_exists('rotina'))
{
function rotina()
{
// Lógica
}
}
And within the actions of their Controllers X and Y just charge the Helper and use:
$this->load->helper('rotina');
// Executa a rotina
rotina();
Show! I had even thought about the issue of helpers, but as it is a somewhat complex routine it did not seem to me that fit well as a "helper", I believe that this idea of Controller Core will suit me, thanks!
– Vinicius Gabriel
Actually, the Helpers help to some extent. Here I use the issue of Heritage a lot because it is much more scalable.
– user134883