Category: Symfony Development

setup vadrant for symfony
Symfony Development

Setup Vagrant For Symfony project on windows

In this tutorial, we have explained how to Setup Vagrant For Symfony project for Windows. Vagrant is a tool for building and managing virtual machine environments in a single workflow. With an easy-to-use workflow and focus on automation, Vagrant lowers development environment setup time, increases production parity, and makes the “works on my machine” excuse a relic of the past. Vagrant is an open-source software product for building and maintaining portable virtual software development environments, e.g., for VirtualBox, KVM, Hyper-V, Docker containers, VMware, and AWS, In this tutorial we are setup vagrant by VirtualBox provider, As VirtualBox is supported to windows. Step 1: Take clone of symfony project First, please take clone of symfony project, for which you want to setup the vagrant Step 2: Take clone of vagrant Repository Please take clone of the vagrant repository, and then please Select the branch specific to what you’re working on ( Navigate to vagrant Folder ) Step 3: Install vagrant plugin Please run the below command, it’ll take few seconds vagrant plugin install vagrant-bindfs If you face this error `bash: vagrant: command not found` during installation of vagrant plugin, first you have to install Vagrant. Step 4: Adjust the artifact path Find the settings.yml file in the Vagrant folder and adjust the artifact path to point to the repositories cloned in steps 1 If you setup this vagrant for symfony then you have to put your project path to app, & if you are working with wordpress then please put to www. Step 5: Add your host-url to host file Add the following lines to your hosts file ( C:\Windows\System32\drivers\etc\hosts ): 192.168.100.100 example.test www.example.test join.example.test Name of the virtual host by which you want to access your project. Note: For open the host file, you have to open as Administration, otherwise will not allow to edit it. Step 6: Install virtualbox Now if you run the `vagrant up`, you’ll face the error, so first you need to install VirtualBox For windows. https://www.virtualbox.org/wiki/Downloads – just click on Windows hosts. Step 7: vagrant up Now feel free to run the command with provideName. vagrant up –provider=virtualbox There will be deprecation warnings and errors, but despite that everything should install okay Step 8: Navigate to project Navigate to https://www.example.test/ ( run this url in browser ). That’s all, now you project run with above host url. Conclusion: I hope this tutorial helpful for you, if you have any issue with setup, please comment below, We will back to you As soon as possible. Thank You! ūüôā
Symfony Development

Installation Webpack Encore bundle Symfony4.4

Before staring installation of Webpack Encore bundle, Let’s take a look in Why this bundle need to be install ?

In earlier version of symfony ( till 3.4 )  we used Assetic Bundle for provides integration of the Assetic library into the Symfony framework.
As of Symfony 4.0, Symfony applications Deprecated this Bundle from Symfony Application.
CAUTION: Now, Symfony applications should use Webpack Encore , instead of Assetic Bundle.

First, make sure you install Node.js and also the Yarn package manager. The following instructions depend on whether you are installing Encore in a Symfony application or not.
Step 1: Install Node.js
https://nodejs.org/en/download/ Form here, you can down load Node.js for  WindowOs as well as MacOs.
Step 2: Yarn Installation
You can install yarn via below command…

npm install -g yarn

Should you later want to update Yarn to the latest version, just run:

yarn set version latest

Step 3: Installing Encore in Symfony Applications
Run these commands to install both the PHP and JavaScript dependencies in your project:

composer require symfony/webpack-encore-bundle
yarn install

If you are using Symfony Flex, this will install and enable the WebpackEncoreBundle, create the assets/ directory, add a webpack.config.js file, and add node_modules/ to .gitignore. You can skip the rest of this article and go write your first JavaScript and CSS by reading Encore: Setting up your Project!

If you are not using Symfony Flex, you‚Äôll need to create all these directories and files by yourself…
Step 4: Configuring Encore/Webpack
Everything in Encore is configured via a webpack.config.js file at the root of your project. It already holds the basic config you need:

The key part is addEntry(): this tells Encore to load the assets/app.js file and follow all of the require() statements. It will then package everything together and Рthanks to the first app argument Рoutput final app.js and app.css files into the public/build directory.

To build the assets, run:

Congrats! You now have three new files:

public/build/app.js¬†(holds all the JavaScript for your ‚Äúapp‚ÄĚ entry)
public/build/app.css¬†(holds all the CSS for your ‚Äúapp‚ÄĚ entry)
public/build/runtime.js (a file that helps Webpack do its job)

Next, include these in your base layout file. Two Twig helpers from WebpackEncoreBundle can do most of the work for you:

{{ encore_entry_link_tags(‘app’) }} & {{ encore_entry_script_tags(‘app’) }}

{{ encore_entry_link_tags(‘app’) }}¬†(For css complied)
{{ encore_entry_script_tags(‘app’) }}¬†(For js complied)

For Example..

Compiling Only a CSS File
If you want to only compile a CSS file, that’s possible via addStyleEntry():

This will output a new some_page.css.

Conclusion:¬†I hope this tutorial helpful for you, if you have any issue regarding this blog, please comment below, we’ll be soon back to you.

Thank You!

 

1
Symfony Development

How to upgrade symfony version from 3.4 to symfony 4.4

Symfony 4: it’s a¬†game¬†changer.¬†Honestly, I’ve¬†never¬†been so excited to start writing tutorials: you are going to¬†love¬†it!
Step 1: Remove Deprecations
look into your project at the bottom you got nav-bar of symfony, something like below.

This is nothing but¬†Deprecations¬†which shows, some functionality or services deprecated in new version, so it’s very important to remove all the listed deprecations before take next step. After removing all the deprecations please see the next step.
Step 2: Version Controller
Now, you are able to upgrade your project/application with the new symfony 4.4, the main changes you should have to do is, change the symfony version in composer.json file.

In older version till¬†3.4 we used¬†`symfony/symfony` bundle , which is deprecated with `symfony/framework-bundle` in symfony 4.4¬†. Now we should use like below…

“symfony/framework-bundle”: “^4.0”

You can manage your version with below reference…

Step 3: Update Composer
After setting-up all deprecations & versions in composer.json, you just need to apply `composer update` command in cmd or git bash.

This command will update/install/remove all the dependencies which is used for described bundle in composer.json file, it’s take few minutes to update¬†dependencies via composer.

Now your project is on symfony4.4 ūüėä.

But still some main steps are remining.
Step 4: Moving to Symfony 4.4 directory structure

The var directory now holds the logs and cache files instead of app directory.
Create the directory in the root folder and move the files in it.

mkdir var
git mv app/cache var/
git mv app/logs var/

To update the project and the changes to take place, make the following changes in app/Appkernel.php

public function getRootDir() { return __DIR__; } public function getCacheDir() { return dirname(__DIR__).’/var/cache/’.$this->environment; } public function getLogDir() { return dirname(__DIR__).’/var/logs’; }

the folder structure something like below

Note :-¬†Please use `git mv` command for change directory structure, do not directly move file via `copy/past` otherwise you’ll face file path in git repository.¬†
That’s all, you are now on symfony4.4, Enjoy your newest symfony version…‚úĆ.

Conclusion:¬†I hope this tutorial helpful for you, if you have any issue regarding this blog, please comment below, we’ll be soon back to you.

Thank You!

 

 

Symfony Development

Paytm Payment Gateway Integration with Symfony : Step by Step

In this tutorial we have explained Paytm Payment Gateway Integration in symfony. Paytm is the good choice for accepting payment online. It is safe, secure, and easy to integrate into website and mobile applications. Nowadays paytm is most popular and famous mobile wallet system. As per the company, over 7 million merchants across India use their QR code payment system to accept payments directly into their bank account.

Nowadays many ecommerce or other service websites start using Paytm payment gateway. Its also reduce the risk to exposing credit card details or banking password. Just send or receive payment via your Mobile Phone. So, no doubt Paytm is better service for online payment for your Website.

Benefits of using Paytm Payment Gateway

Paytm accepts every mode of payment

Paytm Wallet
Bank account via UPI
Debit or Credit cards
Net Banking
EMI Option on cards
Paytm Postpaid

Secure Payments
Industry high success rate
Checkout with saved cards
Real-time bank settlements
Business growth insights on Paytm Merchant Dashboard

Steps to Integrate Paytm Payment Gateway in PHP

Lets start the process of Paytm Payment Gateway Integration. Follow the below steps:

Step 1 : Register for Paytm Account

Sign Up for Paytm bussiness account from here :

Step 2 : Configure Paytm Credential

Add following code in config.yml file.

parameters:

[php]

paytm_marchent_id: "YOUR_MERCHANT_ID"
paytm_marchent_key: "YOUR_MERCHANT_KEY"

[/php]

Step 3 : Create Paytm Integration Helper

Create helper into AppBundle->Helper->PaytmHelper.php
Add following code into PaytmHelper.php

[php]

<?php
namespace AppBundle\Helper;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use AppBundle\Entity\User;

class PaytmHelper {

private $entityManager;
private $container;

public function __construct(EntityManager $entityManager, ContainerInterface $container, Session $session) {
$this->container = $container;
$this->entityManager = $entityManager;
$this->session = $session;
}

//All Functions of Paytm Integration
public function encrypt_e($input, $ky) {
$key = html_entity_decode($ky);
$iv = "@@@@&&&&####$$$$";
$data = openssl_encrypt ( $input , "AES-128-CBC" , $key, 0, $iv );
return $data;
}

public function decrypt_e($crypt, $ky) {
$key = html_entity_decode($ky);
$iv = "@@@@&&&&####$$$$";
$data = openssl_decrypt ( $crypt , "AES-128-CBC" , $key, 0, $iv );
return $data;
}

public function generateSalt_e($length) {
$random = "";
srand((double) microtime() * 1000000);

$data = "AbcDE123IJKLMN67QRSTUVWXYZ";
$data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
$data .= "0FGH45OP89";

for ($i = 0; $i < $length; $i++) {
$random .= substr($data, (rand() % (strlen($data))), 1);
}

return $random;
}

public function checkString_e($value) {
if ($value == ‘null’)
$value = ”;
return $value;
}

public function getChecksumFromArray($arrayList, $key, $sort=1) {
if ($sort != 0) {
ksort($arrayList);
}
$str = $this->getArray2Str($arrayList);
$salt = $this->generateSalt_e(4);
$finalString = $str . "|" . $salt;
$hash = hash("sha256", $finalString);
$hashString = $hash . $salt;
$checksum = $this->encrypt_e($hashString, $key);
return $checksum;
}

public function verifychecksum_e($arrayList, $key, $checksumvalue) {
$arrayList = $this->removeCheckSumParam($arrayList);
ksort($arrayList);
$str = $this->getArray2StrForVerify($arrayList);
$paytm_hash = $this->decrypt_e($checksumvalue, $key);
$salt = substr($paytm_hash, -4);

$finalString = $str . "|" . $salt;

$website_hash = hash("sha256", $finalString);
$website_hash .= $salt;

$validFlag = "FALSE";
if ($website_hash == $paytm_hash) {
$validFlag = "TRUE";
} else {
$validFlag = "FALSE";
}
return $validFlag;
}

public function getArray2Str($arrayList) {
$findme = ‘REFUND’;
$findmepipe = ‘|’;
$paramStr = "";
$flag = 1;
foreach ($arrayList as $value) {
$pos = strpos($value, $findme);
$pospipe = strpos($value, $findmepipe);
if ($pos !== false || $pospipe !== false)
{
continue;
}

if ($flag) {
$paramStr .= $this->checkString_e($value);
$flag = 0;
} else {
$paramStr .= "|" . $this->checkString_e($value);
}
}
return $paramStr;
}

public function getArray2StrForVerify($arrayList) {
$paramStr = "";
$flag = 1;
foreach ($arrayList as $key => $value) {
if ($flag) {
$paramStr .= $this->checkString_e($value);
$flag = 0;
} else {
$paramStr .= "|" . $this->checkString_e($value);
}
}
return $paramStr;
}

public function removeCheckSumParam($arrayList) {
if (isset($arrayList["CHECKSUMHASH"])) {
unset($arrayList["CHECKSUMHASH"]);
}
return $arrayList;
}

public function VerifierChecksum($request){
$data = $request->request->all();
$JsonData =json_encode($data);

$paytmChecksum = isset($data["CHECKSUMHASH"]) ? $data["CHECKSUMHASH"] : "";

$isValidChecksum = $this->verifychecksum_e($data, "&".$this->container->getParameter(‘paytm_marchent_key’), $paytmChecksum);

return $isValidChecksum;

}
}
[/php]

Step 4 : Create Paytm Entity

AppBundle->Entity->PaytmPayment.php

[php]</pre>
<?php

namespace DirectoryPlatform\AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* PaytmPayment
*
* @ORM\Table(name="directory_platform_paytm_payment")
* @ORM\Entity(repositoryClass="DirectoryPlatform\AppBundle\Repository\PaytmPaymentRepository")
*/
class PaytmPayment
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @var int
*
* @ORM\Column(name="orderId", type="integer", length=255)
*/
private $orderId;

/**
* @var int
*
* @ORM\Column(name="userId", type="integer", length=255)
*/
private $userId;

/**
* @var int
*
* @ORM\Column(name="totalAmount", type="integer")
*/
private $totalAmount;

/**
* @var string
*
* @ORM\Column(name="currencyCode", type="string", length=255)
*/
private $currencyCode;

/**
* @var string
*
* @ORM\Column(name="clientEmail", type="string", length=255)
*/
private $clientEmail;

/**
* @var array
*
* @ORM\Column(name="description", type="json_array", length=255)
*/
private $description;

/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}

/**
* Set orderId
*
* @param string $orderId
*
* @return PaytmPayment
*/
public function setOrderId($orderId)
{
$this->orderId = $orderId;

return $this;
}

/**
* Get orderId
*
* @return string
*/
public function getOrderId()
{
return $this->orderId;
}

/**
* Set userId
*
* @param string $userId
*
* @return PaytmPayment
*/
public function setUserId($userId)
{
$this->userId = $userId;

return $this;
}

/**
* Get userId
*
* @return string
*/
public function getUserId()
{
return $this->userId;
}

/**
* Set totalAmount
*
* @param integer $totalAmount
*
* @return PaytmPayment
*/
public function setTotalAmount($totalAmount)
{
$this->totalAmount = $totalAmount;

return $this;
}

/**
* Get totalAmount
*
* @return integer
*/
public function getTotalAmount()
{
return $this->totalAmount;
}

/**
* Set currencyCode
*
* @param string $currencyCode
*
* @return PaytmPayment
*/
public function setCurrencyCode($currencyCode)
{
$this->currencyCode = $currencyCode;

return $this;
}

/**
* Get currencyCode
*
* @return string
*/
public function getCurrencyCode()
{
return $this->currencyCode;
}

/**
* Set clientEmail
*
* @param string $clientEmail
*
* @return PaytmPayment
*/
public function setClientEmail($clientEmail)
{
$this->clientEmail = $clientEmail;

return $this;
}

/**
* {@inheritDoc}
*/
public function getClientEmail()
{
return $this->clientEmail;
}

/**
* {@inheritDoc}
*
* @param array|\Traversable $description
*/
public function setDescription($description)
{
if ($description instanceof \Traversable) {
$description = iterator_to_array($description);
}

$this->description = $description;
}

/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
}
<pre>?>
[/php]

Step 5 : Configure Order controller code

[php]</pre>
/**
* @Route("/accounts/checkout", name="checkout")
*/
public function checkoutAction(Request $request)
{
$baseurl = $request->getScheme() . ‘://’ . $request->getHttpHost() . $request->getBasePath();

// Calculate total price
$products = $request->getSession()->get(‘products’);
if (!$products) {
$this->addFlash(‘danger’, $this->get(‘translator’)->trans(‘Cart is empty. Not able to proceed checkout.’));

return $this->redirectToRoute(‘cart’);
}

$price = 0;
foreach ($products as $product) {
$price += $product[‘price’];
}

// Save order
if ($orderForm->isSubmitted() && $orderForm->isValid()) {
$order = $orderForm->getData();
$order->setStatus(Order::STATUS_NEW);
$order->setUser($this->getUser());
$order->setCurrency($this->getParameter(‘app.currency’));
$order->setPrice($price);

try {
$em = $this->getDoctrine()->getManager();
$em->persist($order);
$em->flush();
} catch (\Exception $e) {
$this->addFlash(‘danger’, $this->get(‘translator’)->trans(‘An error occurred whe saving order.’));
}

// Save order items
foreach ($products as $product) {
$listing = $this->getDoctrine()->getRepository(‘AppBundle:Listing’)->findOneBy([‘id’ => $product[‘listing_id’]]);

$orderItem = new OrderItem();
$orderItem->setOrder($order);
$orderItem->setPrice($product[‘price’]);
$orderItem->setType($product[‘type’]);
$orderItem->setListing($listing);
$orderItem->setDuration($product[‘duration’]);

try {
$em = $this->getDoctrine()->getManager();
$em->persist($orderItem);
$em->flush();
} catch (\Exception $e) {
$this->addFlash(‘danger’, $this->get(‘translator’)->trans(‘An error occurred whe saving order item.’));
}
}

$request->getSession()->remove(‘products’);
$this->addFlash(‘success’, $this->get(‘translator’)->trans(‘Order has been successfully saved.’));

$gatewayName = ‘paytm_standard_checkout’;

$storage = $this->get(‘payum’)->getStorage(Payment::class);

$payment = $storage->create();
$payment->setNumber(uniqid());
$payment->setCurrencyCode($this->getParameter(‘app.currency’));
$payment->setTotalAmount($price * 100);
$payment->setDescription(‘A description’);
$payment->setClientId($order->getUser()->getId());
$payment->setClientEmail($order->getUser()->getEmail());
$payment->setOrder($order);

$storage->update($payment);

$captureToken = $this->get(‘payum’)->getTokenFactory()->createCaptureToken($gatewayName, $payment, ‘paytmcheckout’);

$paytmParams = array(
"MID" => $this->container->getParameter(‘paytm_marchent_id’),
"WEBSITE" => "WEBSTAGING",
"INDUSTRY_TYPE_ID" => "Retail",
"CHANNEL_ID" => "WEB",
"ORDER_ID" => ($order->getId()),
"CUST_ID" => ($order->getUser()->getId()),
"EMAIL" => ($order->getUser()->getEmail()),
"TXN_AMOUNT" => ($price * 100),
"CALLBACK_URL" => $baseurl.$this->generateUrl(‘paytmcheckout’),
);

$checksum = $this->get(‘app.helper.paytm’)->getChecksumFromArray($paytmParams, "&".$this->container->getParameter(‘paytm_marchent_key’));

return $this->render(‘FrontBundle::Paytm/index.html.twig’,
[‘paytmParams’ => $paytmParams,
‘checksum’ => $checksum,
]);
}

return $this->render(‘FrontBundle::Order/checkout.html.twig’, [‘order’ => $orderForm->createView()]);
}

/**
* @Route("/accounts/paytmcheckout", name="paytmcheckout")
*/
//Paytm payment Response function and also use for databse entry.
public function paytmcheckoutAction(Request $request)
{
$token = $this->get(‘app.helper.paytm’)->VerifierChecksum($request);
$status = $request->request->get(‘STATUS’);
$orderId = $request->request->get(‘ORDERID’);

$order = $this->getDoctrine()->getRepository(‘AppBundle:Order’)->findOneBy(array(‘id’ => $orderId));

if($token == "TRUE") {
if ($status == "TXN_SUCCESS") {
$order->setStatus(Order::STATUS_COMPLETED);
$this->addFlash(‘success’, $this->get(‘translator’)->trans(‘Payment has been successful.’));
}else{
$order->setStatus(Order::STATUS_CANCELED);
$this->addFlash(‘danger’, $this->get(‘translator’)->trans(‘Payment has been Failed.’));
}
}else {
$order->setStatus(Order::STATUS_CANCELED);
$this->addFlash(‘danger’, $this->get(‘translator’)->trans(‘Payment has been Failed.’));
}

try {
$em = $this->getDoctrine()->getManager();
$em->persist($order);
$em->flush();
} catch (\Exception $e) {
$this->addFlash(‘danger’, $this->get(‘translator’)->trans(‘An error occurred when saving object.’));
}

return $this->redirectToRoute(‘order’);
}
<pre>
[/php]

Step 6 : Create twig file

[php]</pre>
{% extends ‘FrontBundle::Layout/base.html.twig’ %}

{% block content %}

<body>
<form method="post" action="https://securegw-stage.paytm.in/order/process" name="f1">
<table border="1">
<tbody>

{% for keyVal, paytmParam in paytmParams %}
<input type="hidden" name="{{ keyVal }}" value="{{ paytmParam }}">
{% endfor %}
<input type="hidden" name="CHECKSUMHASH" value="{{ checksum }}">
</tbody>
</table>
<script type="text/javascript">
document.f1.submit();
</script>
</form>
</body>
{% endblock %}
<pre>
[/php]

Conclusion: I hope this tutorial helpful for you, if you have any issue with integration, please comment below.

Thank You!

24
Symfony Development

How To Create Api in Symfony 4 using JSON data ?

Here, I will show you how to create Api in symfony for beginners.
Step 1:
Navigate to project directory & run below command for create fresh project.

composer create-project symfony/skeleton [project-name]
Step 2:
Now Navigate to project path & Create controller via below command.

php bin/console make:controller
Step 3:
Open that controller, now we need to create three methods for api, first of all we look into listing method which make the list of given JSON array [ index() ]

/**
* @Route(“/api/user”, name=”api_user”)
*/
public function index(Request $request)
{
//initilize array
$data = array();
$userArr = array();

// make api request
$request_user_url = ‘../users.json’;
$request_user_result = file_get_contents( $request_user_url );
$user_details = json_decode( $request_user_result, true );

foreach ($user_details as $user)
{
$userArr[‘id’] = $user[‘id’];
$userArr[‘name’] = $user[‘name’];
$userArr[‘date’] = $user[‘date’];
$userArr[‘address’] = $user[‘address’];
$userArr[‘last_modified’] = $user[‘last_modified’];

array_push($data, $userArr);
}

return new JsonResponse(array(‘data’ => $data, ‘count’ => count($data)));
}
Step 4:
Second method for update the JSON data [ update() ]
/**
* @Route(“/api/user-update/{id}/{name}/{date}/{address}”, name=”api_user_update”)
*/
public function update( Request $request, $name = null, $date = null, $address = null )
{
$status = ‘error’;
$message = ‘User not found!’;

$id = $request->get(‘id’);
$name = $request->get(‘name’);
$date = $request->get(‘date’);
$address = $request->get(‘address’);

// make api request
$request_user_url = ‘../users.json’;
$request_user_result = file_get_contents( $request_user_url );
$user_details = json_decode( $request_user_result, true );

foreach ( $user_details as $key => $value )
{
if( $value[‘id’] == $id )
{
if( $name != null )
{
$user_details[$key][‘name’] = $name;
}
if( $date != null)
{
$user_details[$key][‘date’] = $date;
}
if( $address != null )
{
$user_details[$key][‘address’] = $address;
}
$user_details[$key][‘last_modified’] = date(‘Y-m-d H:i:s’);
// updates the specific user..
$status = ‘success’;
$message = ‘User details update successfully!’;
}
}

// encode array to json and save to file
file_put_contents($request_user_url, json_encode($user_details));

return new JsonResponse(array(‘status’ => $status, ‘message’ => $message));
}

Step 5:
Third method for delete the JSON data [ delete() ]
/**
* @Route(“/api/user-delete/{id}”, name=”api_user_delete”)
*/
public function delete(Request $request)
{
$status = ‘error’;
$message = ‘User not found!’;

$userId = $request->get(‘id’);

// make api request
$request_user_url = ‘../users.json’;
$request_user_result = file_get_contents( $request_user_url );
$user_details = json_decode( $request_user_result, true );

foreach ( $user_details as $key => $value )
{
if( $value[‘id’] == $userId )
{
// delete specific user..
unset($user_details[$key]);
$status = ‘success’;
$message = ‘User deleted successfully!’;
}
}

// encode array to json and save to file
file_put_contents($request_user_url, json_encode($user_details));

return new JsonResponse(array(‘status’ => $status, ‘message’ => $message));
}

That’s all, thanks for reading our blog, hope this will help a lot to you.
 

 

Symfony Development

How to create cron in symfony?

Here, I will show you how to create cron in symfony.

Step 1:

Navigate to Project Directory.

Step 2:

create a Cron Task using this command.

php bin/console make:command app:[cron-name]

and it will generate a [cron-name]Command.php.

this file have two methods : configure() and execute().

Step 3 – Configuration:

in configure method, there are some configuration in this method like description, argument, and options.

$this->setDescription(‘Add a short description for your command’)
->addArgument(‘arg1’, InputArgument::OPTIONAL, ‘Argument description’)
->addOption(‘option1’, null, InputOption::VALUE_NONE, ‘Option description’)
;

Step 4 – Execution :

In execute method have some code that will be execuated.

protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$arg1 = $input->getArgument(‘arg1’);

if ($arg1) {
$io->note(sprintf(‘You passed an argument: %s’, $arg1));
}

if ($input->getOption(‘option1’)) {
// …
}

$io->success(‘You have a new command! Now make it your own! Pass –help to see your options.’);

return Command::SUCCESS;
}

Step 5 – Run Cron :

Now Open a command-line and run this command
`php bin/console app:[cron-name]`

now its have an output.

Thanks for reading.

Symfony Development

Symfony Development

In Symfony 4.2, locks can be stored in PDO-compatible databases like MySQL, MariaDB and PostgreSQL.

Symfony Development

Symfony Development

Symfony 4.2 introduces a new VarExporter component to provide a better alternative to PHP’s var_export() function.

Symfony Development

Symfony Development

Symfony is a PHP framework as well as a set of reusable PHP components and libraries. It uses the Model-View-Controller design pattern and can be scaled to be used in any requirement.