Why Symfony and Sylius Are the Most Powerful Combination for Building E-commerce Platforms
Why Use Coding Standards in Web Development: A Symfony Perspective
Why Symfony is the Best PHP Framework for Modern Web Development
Enum in Symfony
composer create-project symfony/skeleton new-test-app
symfony new new-test-app --full
cd /new-test-app
symfony server:start
composer require elao/enum
<?php
declare(strict_types=1);
namespace App\DBAL\Types;
use BackedEnum;
use Elao\Enum\ReadableEnumInterface;
interface SQLEnumTypeInterface extends ReadableEnumInterface, BackedEnum
{
public function getExcludeFromSQLEnumDeclaration(): bool;
}
<?php
declare(strict_types=1);
namespace App\DBAL\Types;
interface SQLEnumTypeDefaultForNullInterface extends SQLEnumTypeInterface
{
public static function getDefaultForNull(): self;
}
<?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;
}
}
<?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);
}
}
<?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;
}
}
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' ]
<?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);
}
}
<?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';
}
<?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;
}
}
<?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;
}
}
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
Setup Vagrant For Symfony project on windows
Note: For open the host file, you have to open as Administration, otherwise will not allow to edit it.
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!
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!
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!
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.