Access shell methods in controller? Cake PHP 1.3
I wrote a shell method in CakePHP 1.3 that has a return value.
I'd like to be able to access that method from within a controller, so that I can pass its return value into the View.
I'm not sure how to access those methods appropriately from within the controller. Have I done it w开发者_开发百科rong?
I could easily duplicate the code, but I'd like to "keep it DRY", and the actual functionality, I believe, doesn't belong with this particular controller - I just need it's return value in this particular view.
EDIT:
I realize I'm sort of asking the wrong question here, since the Shell itself shouldn't necessarily return a value. I've changed the code so that the Shell is only using the return value I want, and now I wonder - what is the appropriate place for extra classes/code that needs to be accessed from a Shell and a Controller?
It seems like Component code, but I'm not sure how to access Components from the Shell. It's not a Plugin, as I understand them. Where does this go?
In one of the projects we imported shell tasks, ex:
App::import('Core', 'Shell');
App::Import('Vendor','shells/tasks/sometask');
$returndata = TasknameTask::execute($somevalue);
You can create a component to do that.E.g
/* in app/controllers/components */
class ShellComponent extends Object
{
function do_shell()
{
return shell_exec('some command');
}
}
Then use it in any controller you want as below
/* in some controller*/
var $components = array('Shell','maybe some other components',....);
function testShell()
{
$result = $this->Shell->do_shell();
....
}
Shells shouldn't directly return a value explicitly, they ought to report it somehow, e.g. by echoing it to stdout, logging to a file or sending an email for example. I like to think of shells as controllers for the cli.
Without knowing your application, my suggestion would be to see if you could refactor the logic in your current shell into a model class or something like that, have the model method return the value, then use that model in your shell. This way, you can also use that model in your controller.
The accepted answer doesn't seems to work for Cake 2.0
For Cake 2.0
if (!class_exists('Shell')) {
require CONSOLE_LIBS . 'shell.php';
}
App::import('Shell', 'DoSomething');
DoSomethingShell::main();
Bear in mind some Shell method doesn't work in this mode, such as $this->out, so more hacking is required.
精彩评论