tags:

views:

48

answers:

2

Hi,

Is it possible to capture the output of an action in a task?

Ex:

FooAction { executeIndexSuccess() }

and in my Task:

FooAction->Index

Is this possible?

Thanks

+1  A: 

Yes. In your task's execute() method:

sfContext::createInstance($this->configuration);
$output = sfContext::getInstance()->getController()->getPresentationFor("module", "action");

The resultant output from the action and associated view will be stored in $output.

If your action needs variables setting into the session, you can also do things like:

sfContext::getInstance()->getUser()->setAttribute("mySessionVar", 123);
sfContext::getInstance()->getUser()->setFlash("myFlashVar", "foo");

before you call getPresentationFor(), so that the variables are present when the action is executed.

richsage
A: 

You should not do this in a task! Controller actions are not build for such purpose. Just refactor your Controller. Extract the code you need to share with the task to a seperate class and use this class in your action and the task! Keep in mind that the sfContext is not a reliable source of information. The content of this object depends on how your application is started (Commandline != HTTP)

Timo
sfContext isn't reliable or ideal, you're correct. However, I think there are many applications for getting the controller output in tasks - automated HTML emails using a standard layout decorator is one example that springs to mind. You might as well use the MVC-style structure that's provided :-)
richsage
That's exactly what I'm looking to do: I want to set up a task which will send e-mails based on what's in the database, and this is run in a cron script. Basically do this all in an asynchronous manner. So now, when you say "use the MVC-style structure, what exactly are you referring to?
Paul
You are right for HTML-Emails you will need some of the view parts of Symfony and a sfContext as well. But even if you want to send an E-Mail I would prefer to render a partial in the Task insteas of using the Action-Method, so you will not depend on the request/response handling and can use templates to generate the E-Mail.
Timo
@Paul - obviously in Symfony you have a model-view-controller-style stack. So, in an HTML email case, you could do any logic required (retrieving a user's profile details etc) in the action and the presentation in the view, same as you would for a web page including any layout decorators, partials etc. Then capture the output via the method in my answer, and despatch via SwiftMailer or similar.
richsage