Reputation: 2936
I'm learning the Symfony2 framework and was wondering if there was a way to create scripts that can be run from the command line OR the web front controller. I know this is unusual, but there are some special cases where I like to develop a script with web output, and then run it later using the command line with no output. My first thought would be to create a controller that is called by a route and also used in a Command object. Is that the best way to design it?
Upvotes: 0
Views: 73
Reputation: 47585
Extract your logic to a service, a class.
class DoSomethingAwesome
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function actuallyDoSomethingAwesome($param)
{
// your logic
}
}
then define a service:
<service id="awesome.service" class="DoSomethingAwesome">
<argument id="logger" type="service" />
</service>
And then, inject your service in your command and controller, or if you use a naive and default implementation get it directly from the container:
class SomeController extends Controller
{
public function someAction()
{
$this->get('awesome.service')->actuallyDoSomethingAwesome();
}
}
class SomeCommand extends ContainerAwareCommand
{
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->container->get('awesome.service')->actuallyDoSomethingAwesome();
}
}
Upvotes: 0
Reputation: 1487
The best way would be to implement your business logic in a Service, create a Controller action which runs it and also create a ContainerAwareCommand which runs it too. Pretty straight-forward :)
Upvotes: 1