ianmjones
ianmjones

Reputation: 3415

How do I test whether running from CakePHP Console?

I have a CakePHP Console Shell that works fine until a Model->afterFind() tries to add some data to the results which includes adding links, which doesn't seem to work while being called from the Console.

Is there a way to test in the Model->afterFind() callback function whether it's being called from a Console Shell, so that I can skip the troublesome section that I don't need anyway?

Thanks, Ian

Upvotes: 4

Views: 1206

Answers (2)

JohnP
JohnP

Reputation: 50039

I'm not too sure whether there's a Cake way to do it, but you can do it via regular PHP

 if(php_sapi_name() == 'cli' && empty(getClientIP())) {
      //running via CLI
 } else {
      //running normally
 } 

Upvotes: 6

Tyler
Tyler

Reputation: 2126

It seems to me that you're breaking MVC best-practices if your business (model) layer is having adverse effects when run in different contexts. Whatever you're putting into Model->afterFind() should be completely agnostic to how the application is executed.

With that understood, the model layer of CakePHP is not at all aware of the execution context. One solution would be to deal with this by passing a flag to the model layer from the shell. ie:

At the top of app_model.php:

var $isShellContext = false;

Then, in your shell:

$this->Model->isShellContext = true;

And then in Model->afterFind():

if(!$this->isShellContext) {
   // add links, etc
}

Upvotes: 2

Related Questions