I would use the PHPExcel bundle other than in a controller (to create a service), but I can not get it to work under these conditions.
Here is what I have written in the function 'execute' of the command file:
class XportXcelPourAnalyseCommand extends ContainerAwareCommand
....
protected function execute(InputInterface $input, OutputInterface $output){
....
$phpExcelObject = $this->getContainer('phpexcel')->createPHPExcelObject();
$phpExcelObject->getProperties()->setCreator("liuggio")
->setLastModifiedBy("Giulio De Donato")
->setTitle("Office 2005 XLSX Test Document")
->setSubject("Office 2005 XLSX Test Document")
->setDescription("Test document for Office 2005 XLSX, generated using PHP classes.")
->setKeywords("office 2005 openxml php")
->setCategory("Test result file");
$phpExcelObject->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!');
$phpExcelObject->getActiveSheet()->setTitle('Simple');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$phpExcelObject->setActiveSheetIndex(0);
// create the writer
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
// create the response
$response = $this->get('phpexcel')->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'stream-file.xls'
);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
$output->writeln('done');
}
when you create a command by following docs your command class inherits ContainerAwareCommand class and you can get the container by calling $this->getContainer() inside the execute() function of your command class, once you have container you can access any service like to get the excel service you can get it like $this->getContainer()->get('phpexcel')
class GenerateExcelCommand extends ContainerAwareCommand
{
protected function configure()
{
//..............
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$excelObj= $this->getContainer()->get('phpexcel');
// do your excel stuff here
$phpExcelObject = $excelObj->createPHPExcelObject('file.xls');
$writer = $excelObj->createWriter($phpExcelObject, 'Excel5');
$writer->save('file.xls');
$output->writeln('done');
}
}
By using ContainerAwareCommand as the base class for the command (instead of the more basic Command), you have access to the service container. In other words, you have access to any configured service
Getting Services from the Service Container
Related
I tried to understand how this works since more than a day, and I'm totally confused right now.
Here is my (very simple) goal: make a GET request on a URL when I receive a new email.
I have created a topic as they asked (named new-email)
I have a subscription in that topic (named new-email-inbox), with delivery type push, and setting my endpoint URL.
I gave my subscription authorization to this account: gmail-api-push#system.gserviceaccount.com (Editor & Editor Pub/Sub)
How do I set up the rest ? I don't understand what to do now..
I did a Symfony4 command, executed everyday like a cron:
class WatchGoogleClient extends Command {
private $kernel;
private $gmailService;
public function __construct(GmailService $gmailService, Kernel $kernel)
{
parent::__construct();
$this->gmailService = $gmailService;
$this->kernel = $kernel;
}
protected function configure()
{
$this->setName('app:watch-google-client')
->setDescription('watch-google-client')
->setHelp('Reset the google watch timer');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// This getClient function is basically what is given by the google API tutorial
$client = $this->gmailService->getClient($this->kernel);
$service = new \Google_Service_Gmail($client);
$watchreq = new \Google_Service_Gmail_WatchRequest();
$watchreq->setLabelIds(array('INBOX'));
$watchreq->setTopicName('YOUR_TOPIC_NAME');
$msg = $service->users->watch('me', $watchreq);
var_dump($msg);
// DO WHAT YOU WANT WITH THIS RESPONSE BUT THE WATCH REQUEST IS SET
}
}
I am developing a SilverStripe project. I am trying to create a task to run through accessing the dev/tasks URL but the task I have created is not showing up in the tasks list.
In the code folder I have created a file SayHiTask with the following code:
class SayHiTask extends MigrationRecord
{
protected $title = 'Say Hi';
protected $description = 'A class that says <strong>Hi</strong>';
protected $enabled = true;
function run($request) {
echo "I'm trying to say hi...";
}
}
I then build the project again by visiting dev/build?flush=all. Then, when I go to dev/tasks, the task is not displayed in the list.
What is wrong and what did I miss?
To make a custom build task we need to extend the BuildTask class:
use SilverStripe\Dev\BuildTask;
class SayHiTask extends BuildTask
{
protected $title = 'Say Hi';
protected $description = 'A class that says Hi';
protected $enabled = true;
public function run($request)
{
echo "I'm trying to say hi...";
}
}
Once we have this code we visit dev/tasks?flush=all and our Say Hi dev task will appear in the list of available tasks.
I try to send mail (swiftmail) via command of symfony.
Here is my code :
class CommandMail extends Command
{
protected static $defaultName = 'app:send-daily-mail';
protected function configure() {
$this
->setDescription('Send automatic reminders mail everyday.')
->setHelp('This command allows you to send automatic reminder mail to Rhys, everyday...');
}
protected function execute(InputInterface $input, OutputInterface $output) {
$message = (new \Swift_Message('test auto mail cron 12 24 TEST'))
->setFrom('xxxxxx.xxxxxxx#gmail.com')
->setTo('wwwww.wwwwwww#gmail.com')
->setBody('test body');
$this->get('mailer')->send($message);
}
}
I have following error :
In CommandMail.php line 54:
Attempted to call an undefined method named "get" of class
"AppBundle\Command\CommandMail".
Did you mean to call e.g. "getAliases", "getApplication",
"getDefaultName", "getDefinition", "getDescription", "getHelp",
"getHelper", "getHelperSet", "getName", "getNativeDefin ition",
"getProcessedHelp", "getSynopsis" or "getUsages"?
I try many things (getContainer() ie and many others) but nothing is working.
Thanks for your help !
(Symfony 3, SMTP gmail)
If you are using Symfony 4, inject the dependency by constructor:
private $swiftMailerService;
public function __construct(\Swift_Mailer $swiftMailerService)
{
parent::__construct();
$this->swiftMailerService = $swiftMailerService;
}
protected function execute(InputInterface $input, OutputInterface $output) {
$message = (new \Swift_Message('test auto mail cron 12 24 TEST'))
->setFrom('xxxxxx.xxxxxxx#gmail.com')
->setTo('wwwww.wwwwwww#gmail.com')
->setBody('test body');
$this->swiftMailerService->send($message);
}
I have a command connecting to an external database and loading the data into my application's database. The command will run periodically as a cron job. However, I run into the following problem when I run the command in the console:
PHP Fatal error: Call to undefined method Symfony\Component\Console\Application::getKernel() in E:\www\project\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand.php on line 43
I followed the tutorial here on symfony's website to the letter.
Here's the service definition:
app.command.get_transactions:
class: AppBundle\Command\TransactionsCommand
arguments: [ #doctrine.orm.entity_manager ]
tags:
- { name: console.command }
Here's my command code:
<?php
namespace AppBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use AppBundle\Entity\Transaction;
use AppBundle\Entity\TransactionSync;
use Doctrine\DBAL\DriverManager;
class TransactionsCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('transactions:get')
->setDescription('Import transactions')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get('doctrine')->getManager();
$q = $em->createQueryBuilder();
$q->select('t')->from('AppBundle:TransactionSync', 't')->orderBy('t.id', 'DESC')->setMaxResults(1);
$sync = $q->getQuery()->getResult();
$em1 = $this->getContainer()->get('doctrine')->getManager('rnr');
$conn = $em1->getConnection();
$query = "SELECT id, merchant, client, phone, traderTransIdent AS member_id, transaction_id, transaction_type_id, value AS amount, points, DATE_FORMAT(STR_TO_DATE( transaction_date, '%d-%m-%Y' ), '%Y-%m-%d') AS transaction_date FROM merchant_transactions WHERE id > ". $sync->getId();
$stmt = $conn->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if(count($results) > 1)
{
$ts = new TransactionSync();
$ts->setStartTime(new \DateTime());
$id = 0;
foreach($results as $result)
{
$transaction_type = $em->getRepository('AppBundle:TransactionType')->find($result['transaction_type_id']);
$member = $em->getRepository('AppBundle:Member')->find($result['member_id']);
$transaction = new Transaction();
$transaction->setAmount($result['amount']);
$transaction->setPoints($result['points']);
$transaction->setClient($result['client']);
$transaction->setPhone($result['phone']);
$transaction->setTransactionId($result['transaction_id']);
$transaction->setTransactionDate(new \DateTime($result['transaction_date']));
$transaction->setTransactionType($transaction_type);
$transaction->setMember($member);
$em->persist($transaction);
$id = $result['id'];
}
$ts->setLastId($id);
$ts->setRecords(count($results));
$ts->setEndTime(new \DateTime());
$em->persist($ts);
$em->flush();
}
$output->writeln($text);
}
}
According to the accepted answer here and many other places online I have seen, extending ContainerAwareCommand should solve this but I still keep getting the error. Please assist in pointing the step I missed, I'll be very grateful
Remove your service definition, as you put your command inside Command folder and extended ContainerAwareCommand you don't need to use any tags and inject entity manager.
ContainerAware has been deprecated in 4.2. It's saying now:
The ContainerAwareCommand class has been deprecated. It was used in
the past to create commands extending from it so they had direct
access to the app service container. The alternative is to extend
commands from the Command class and use proper service injection in
the command constructor.
https://symfony.com/blog/new-in-symfony-4-2-important-deprecations
I've a file in testBundle>Command>ReportCommand.php where I want to set flash message like below but it's not working. I've also added this namespace but it didn't work too:-use Symfony\Component\HttpFoundation\Request;
$this->get('session')->getFlashBag()->add(
'notice', sprintf('%s email sent!', str_replace('_', ' ', ucfirst($type)))
);
You cannot use sessions from command line, you can only use them with the HTTP way. Try to store your message in a différent way :
In a file
In your MySQL database
In a RAM cache (E.g. redis)
etc...
You can use outer interface to show the message on command prompt.
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class classname extends ContainerAwareCommand {
protected function configure()
{
// command details
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// your script code
$output->writeln("Your message");
}
}