Category: Symfony Development

enum in symfony
Symfony Development Uncategorized

Enum in Symfony

Hey folks, I hope you are doing well. In this post, we are going to understand what enums are and how we can use enum in Symfony. Before we go through, let’s understand what an enum is. What is Enum? Enums, short for enumerations, are a data type that allows you to define a set of named values. They are useful for representing fixed sets of related constants, improving code readability, and ensuring type safety. In Symfony, enums can help you manage state, roles, and other sets of predefined values more effectively. Why Use Enums? Readability: Enums replace magic numbers and strings with descriptive names. Type Safety: Enums restrict variables to predefined values, reducing errors. Maintainability: Centralized definition makes it easy to update values in one place. How to Use Enum in Symfony? Symfony does not provide a data type for enums, so which data types does Symfony provide us? Let’s see. Create a Symfony App: I hope you know how to create a Symfony app. If not, just follow my lead; I’ll explain everything to you.As per the Symfony documentation, you can create a Symfony app in different ways. The first way is to create an app using Composer, and another way is to create an app using Symfony CLI. you can follow Symfony documentation for more details. here are commands you can use to create an app.
composer create-project symfony/skeleton new-test-app
or
symfony new new-test-app --full
now move into your new app directory and start the local server as follows.
cd /new-test-app

symfony server:start
once your server starts you can click on the link, which will be 127.0.0.1:8000, the port can be different, after you open that page, you will see a page like this. Now let’s create an entity in which we are going to use an enum. Run the command in the terminal where your project directory exists. Once you install the package, run the make:entity command again, which I have added above. create an entity for user, from the make: entity command and add following fields. username: Name: username Type: string Length: 150 Not Null: Yes password: Name: password Type: string Length: 255 Not Null: Yes role: Name: role type: for type just type ? and enter, and you will see datatypes provided by Symfony. Symfony does not provide a built-in enum datatype. However, we can explore alternative methods to achieve similar functionality in Symfony. Let’s explore our options. Enum in Symfony: we are going to create a custom enum type field in Symfony, so we will create a Custom Doctrine Type for Enums, we’ll call that class AbstractEnumType. before that install this package which we will use to create enum classes.
composer require elao/enum
create a new directory inside the src folder of your app, called DBAL in which we can create custom datatype fields for our app, in that directory we’ll need to create two more directories one is TypedFieldMapper, and another one is Types. create a new Interface in the Types directory, called SQLEnumTypeInterface.
<?php

declare(strict_types=1);

namespace App\DBAL\Types;

use BackedEnum;
use Elao\Enum\ReadableEnumInterface;

interface SQLEnumTypeInterface extends ReadableEnumInterface, BackedEnum
{
    public function getExcludeFromSQLEnumDeclaration(): bool;
}
now create another interface in the Types directory called SQLEnumTypeDefaultForNullInterface.
<?php

declare(strict_types=1);

namespace App\DBAL\Types;

interface SQLEnumTypeDefaultForNullInterface extends SQLEnumTypeInterface
{
    public static function getDefaultForNull(): self;
}
now create AbstractClass in the Types directory for Enum Type.
<?php

declare(strict_types=1);

namespace App\DBAL\Types;

use BackedEnum;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SqlitePlatform;
use Doctrine\DBAL\Types\Type;
use LogicException;

abstract class AbstractEnumType extends Type
{
    /** @return class-string<SQLEnumTypeInterface> */
    abstract public static function getEnumClass(): string;

    public function getName(): string // the name of the type.
    {
        return static::getEnumClass();
    }

    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
    {
        $class = static::getEnumClass();

        if (!is_a($class, SQLEnumTypeInterface::class, true)) {
            throw new LogicException(sprintf('%s must be of %s type', $class, SQLEnumTypeInterface::class));
        }

        $values = [];

        foreach ($class::cases() as $val) {
            if (!$val->getExcludeFromSQLEnumDeclaration()) {
                $values[] = "'{$val->value}'";
            }
        }

        if ($platform instanceof SqlitePlatform) {
            return "TEXT CHECK( " . $column['name'] . " IN (" . implode(", ", $values) . ") )";
        }

        return "enum(" . implode(", ", $values) . ")";
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform): mixed
    {
        if ($value !== null && !($value instanceof BackedEnum)) {
            /** @var SQLEnumTypeInterface $class */
            $class = static::getEnumClass();
            $value = $class::tryFrom($value);
        }

        if ($value instanceof SQLEnumTypeDefaultForNullInterface && $value === $value::getDefaultForNull()) {
            return null;
        }

        if ($value instanceof SQLEnumTypeInterface) {
            if ($value->getExcludeFromSQLEnumDeclaration()) {
                throw new LogicException(sprintf('%s is not a valid value for %s in database', $value->value, get_debug_type($value)));
            }

            return $value->value;
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform): ?BackedEnum
    {
        if (false === enum_exists(static::getEnumClass(), true)) {
            throw new LogicException("This class should be an enum");
        }

        /** @var SQLEnumTypeInterface $class */
        $class = static::getEnumClass();

        if (is_a($class, SQLEnumTypeDefaultForNullInterface::class, true) && $value == null) {
            /** @var SQLEnumTypeDefaultForNullInterface $class */
            return $class::getDefaultForNull();
        }

        if ((!is_int($value)) && !is_string($value)) {
            return null;
        }

        return $class::tryFrom($value);
    }

    /**
     * @codeCoverageIgnore
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform): bool
    {
        return true;
    }
}

create a new Trait for the enum,
<?php

declare(strict_types=1);

namespace App\DBAL\Types;

use Elao\Enum\ExtrasTrait;
use Elao\Enum\ReadableEnumTrait;

trait SQLEnumTypeTrait
{
    use ReadableEnumTrait;
    use ExtrasTrait;

    public function getExcludeFromSQLEnumDeclaration(): bool
    {
        return !!$this->getExtra('excludeFromSQLEnumDeclaration', false);
    }
}
and create a new class inside TypeFieldMapper called AbstractEnumMapper, this class will map the enum type field into doctrine.
<?php

declare(strict_types=1);

namespace App\DBAL\TypedFieldMapper;

use App\DBAL\Types\SQLEnumTypeInterface;
use Doctrine\ORM\Mapping\TypedFieldMapper;
use ReflectionNamedType;
use ReflectionProperty;

class AbstractEnumMapper implements TypedFieldMapper
{
    public function validateAndComplete(array $mapping, ReflectionProperty $field): array
    {
        $type = $field->getType();
        if (
            ! isset($mapping['type'])
            && ($type instanceof ReflectionNamedType)
        ) {
            if (!$type->isBuiltin() && enum_exists($type->getName()) && is_subclass_of($type->getName(), SQLEnumTypeInterface::class)) {
                $mapping['type'] = $type->getName();
            }
        }

        return $mapping;
    }
}
now we need to register our classes in service.yaml file which is exist inside config directory.
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
    _instanceof:
        App\DBAL\Types\AbstractEnumType:
            tags: [ 'app.doctrine_enum_type' ]

    App\DBAL\TypedFieldMapper\AbstractEnumMapper:

    Doctrine\ORM\Mapping\DefaultTypedFieldMapper:

    Doctrine\ORM\Mapping\ChainTypedFieldMapper:
        arguments:
            $typedFieldMappers:
                - '@App\DBAL\TypedFieldMapper\AbstractEnumMapper'
                - '@Doctrine\ORM\Mapping\DefaultTypedFieldMapper'

    doctrine.orm.configuration:
        class: Doctrine\ORM\Configuration
        calls:
            - setTypedFieldMapper: [ '@Doctrine\ORM\Mapping\ChainTypedFieldMapper' ]
now one final thing we need to do is to register all the enums that we created in to kernel, so every time we create a new enum we don’t need to write them into doctrine.yaml file, we’ll do that from the kernel.
<?php

declare(strict_types=1);

namespace App;

use App\DBAL\Types\AbstractEnumType;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;

class Kernel extends BaseKernel implements CompilerPassInterface
{
    use MicroKernelTrait;

    public function process(ContainerBuilder $container): void
    {
        $typesDefinition = [];
        if ($container->hasParameter('doctrine.dbal.connection_factory.types')) {
            /** @var array $typesDefinition */
            $typesDefinition = $container->getParameter('doctrine.dbal.connection_factory.types');
        }

        $taggedEnums = $container->findTaggedServiceIds('app.doctrine_enum_type');

        foreach ($taggedEnums as $enumType => $definition) {
            /** @var AbstractEnumType $enumType */
            $typesDefinition[$enumType::getEnumClass()] = ['class' => $enumType];
        }

        $container->setParameter('doctrine.dbal.connection_factory.types', $typesDefinition);
    }
}
now we’ve configured the enum in symfony how do we use them? let’s see. using enums in symfony: create a new directory inside your Entity directory. which we’ll use to create Enum classes, so we’ll call this directory Enum, and create a new Enum class UserRole.
<?php

declare(strict_types=1);

namespace App\Entity\Enum;

use App\DBAL\Types\SQLEnumTypeInterface;
use App\DBAL\Types\SQLEnumTypeTrait;
use Elao\Enum\Attribute\EnumCase;

enum UserRole: string implements SQLEnumTypeInterface
{
    use SQLEnumTypeTrait;

    #[EnumCase('Admin')]
    case ADMIN = 'ROLE_ADMIN';

    #[EnumCase('User')]
    case USER = 'ROLE_USER';
}

now create another file inside the Types Directory, called UserRoleType.
<?php

declare(strict_types=1);

namespace App\DBAL\Types;

use App\Entity\Enum\UserRole;

class UserRoleType extends AbstractEnumType
{
    public static function getEnumClass(): string
    {
        return UserRole::class;
    }
}
now run the make:entity command and enter your class name which we have created at the starting, so use the User class add a new field role, and again type ? and hit enter, you will see our newly created enum class there and also you can assign this datatype to role. here is User Entity,
<?php

namespace App\Entity;

use App\Entity\Enum\UserRole;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`')]
class User
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 150)]
    private ?string $username;

    #[ORM\Column(length: 255)]
    private ?string $password;

    #[ORM\Column(type: UserRole::class)]
    private UserRole $role;

    public function getId(): int
    {
        return $this->id;
    }

    public function getUsername(): string
    {
        return $this->username;
    }

    public function setUsername(string $username): static
    {
        $this->username = $username;

        return $this;
    }

    public function getPassword(): string
    {
        return $this->password;
    }

    public function setPassword(string $password): static
    {
        $this->password = $password;

        return $this;
    }

    public function getRole(): UserRole
    {
        return $this->role;
    }

    public function setRole(UserRole $role): static
    {
        $this->role = $role;

        return $this;
    }
}

now if you run the make:migration command in which you can see thet we’ve successfully used enum in Symfony.
CREATE TABLE `user` (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(150) NOT NULL, password VARCHAR(255) NOT NULL, role enum(\'ROLE_ADMIN\', \'ROLE_USER\') NOT NULL COMMENT \'(DC2Type:App\\\\Entity\\\\Enum\\\\UserRole)\', PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
now, we’ve successfully implemented Enum in Symfony, if you want to learn how to add a cron job in Symfony you can check it from here.
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! 🙂
1
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!

 

4
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:

Step 3 : Create Paytm Integration Helper

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

Step 4 : Create Paytm Entity

AppBundle->Entity->PaytmPayment.php

Step 5 : Configure Order controller code

Step 6 : Create twig file

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

Thank You!

38
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.

5
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.

×