Category: Symfony Development

Symfony Development

Guide to Upgrading Symfony from an Old Version to a New Version: A Step-by-Step Approach

Upgrading your Symfony project to a newer version, like Symfony 6.4 or 7.1, can seem daunting. However, with a structured plan, you can ensure a smooth transition while taking advantage of the latest Symfony features. This guide walks you through the essential steps to upgrade your Symfony application. 1. Create a New Repository Begin by creating a new repository for the upgrade process. This approach allows you to work independently, safeguarding your production environment from accidental disruptions. 2. Set Up a Fresh Symfony Project Install a new Symfony project with your desired version: composer create-project symfony/skeleton my_project This fresh setup will act as the base for your migration, providing a clean slate for compatibility testing. 3. Copy Composer Files from the Old Project Copy the composer.json and composer.lock files from your old project to the new one. Use Packagist to check for updated versions of dependencies and ensure they are compatible with the new Symfony version. 4. Review and Adjust Package Dependencies Examine the dependencies in your composer.json file. Update or replace any deprecated or outdated packages to align with Symfony’s latest version. After making adjustments, run: composer update 5. Migrate Custom Bundles Copy custom bundles from the old project to the new project’s src/ directory. Symfony’s newer versions favor services over the traditional bundle system, so refactor as needed. 6. Run Composer Update Once dependencies are updated and bundles are added, run the following command to install the required versions: composer update Ensure the config/packages/ directory contains modular configuration files for each bundle or feature. 7. Update Configuration Files Symfony versions 4 and later encourage splitting centralized configurations. Break down your old config.yml file into multiple YAML or PHP files under config/packages/. 8. Update Database Configuration Adjust your database configuration in doctrine.yaml to match the new version’s requirements. Register entity paths properly if your project uses custom bundles. doctrine: orm: mappings: App: is_bundle: false type: annotation dir: '%kernel.project_dir%/src/Entity' prefix: 'App\Entity' 9. Refactor Entities and Repositories Switch from annotations to PHP 8 attributes in your entities and repositories. Symfony 6 and 7 fully embrace attributes for ORM mapping. Example: #[ORM\Entity] class Product { #[ORM\Id, ORM\Column(type: "integer"), ORM\GeneratedValue] private int $id; } 10. Run Doctrine Migrations After updating your entities, generate and execute database migrations: php bin/console doctrine:migrations:diff php bin/console doctrine:migrations:migrate Verify that no unnecessary queries are generated to maintain database performance. 11. Register Twig Bundles If your project uses Twig bundles, register them in twig.yaml with the correct namespaces to avoid conflicts. 12. Update Custom Twig Extensions Review custom Twig extensions, filters, or functions. Ensure they’re compatible with Symfony’s latest service handling and address any deprecated features. 13. Migrate Routing Configuration Update your routing configuration to a modular structure. Use attributes for routing instead of annotations: Old: /** * @Route("/example", name="example") */ public function example() {} New: #[Route('/example', name: 'example')] public function example() {} 14. Refactor Controllers Refactor controllers to follow modern Symfony conventions. Use a BaseController for shared functionalities and update Twig rendering syntax. Example: return $this->render('template.html.twig', ['data' => $data]); 15. Fix Code Standards and Deprecations Symfony 6 and 7 prioritize modern PHP practices. Update your code to: Use type declarations. Follow PHP 8.x standards. Handle exceptions properly. Address all deprecation warnings using: php bin/console debug:container –deprecations 16. Final Testing and Debugging Run comprehensive tests to ensure everything works as expected. Address errors and remove deprecated features to achieve a fully functional and modern application. Benefits of Upgrading Symfony Improved Security: Stay protected with the latest updates. Enhanced Performance: Benefit from optimized code and faster execution. Modern PHP Features: Embrace PHP 8 attributes, type declarations, and more. Long-Term Support: Keep your project relevant and supported. Final Thoughts Upgrading your Symfony application can seem complex, but following these step-by-step instructions will make the process manageable. A successful migration ensures your application is modern, secure, and performant. Start your Symfony upgrade journey today!
Sylius Symfony Development

Why Symfony and Sylius Are the Most Powerful Combination for Building E-commerce Platforms

When it comes to building an e-commerce platform, choosing the right tools is essential. Symfony, a high-performance PHP framework, and Sylius, an open-source e-commerce solution built on Symfony, form a dynamic duo that empowers developers to create highly customizable and scalable online stores. What is Symfony? Symfony is a robust PHP framework known for its flexibility, modularity, and adherence to best practices. It is widely used to build complex applications across various domains, and its ecosystem is backed by a vibrant community. What is Sylius? Sylius is a powerful e-commerce platform based on Symfony. It provides a headless and API-first architecture, allowing developers to build custom e-commerce experiences tailored to specific business needs. It includes essential e-commerce features out-of-the-box, like: Product management Order processing Customer accounts Payment gateways Inventory management Why Choose Symfony and Sylius for E-commerce? 1. Flexibility and Customizability Symfony’s component-based architecture allows developers to use only the parts they need, ensuring optimal performance. Sylius extends this flexibility by enabling developers to customize every aspect of their e-commerce store, from product attributes to checkout workflows. 2. API-First Approach Sylius adopts an API-first strategy, making it ideal for headless e-commerce setups. This means you can build custom frontends using frameworks like React, Vue.js, or Angular, while Sylius handles backend processes seamlessly. 3. Scalability Symfony’s robust architecture and Sylius’s modular design make this duo perfect for businesses of all sizes. Whether you’re running a small online shop or a global enterprise, this stack can handle your growth. 4. Developer-Friendly Both Symfony and Sylius prioritize developer experience: Symfony’s reusable components and extensive documentation simplify development. Sylius’s clear architecture and integration with Symfony’s best practices make customization straightforward. 5. Rich Ecosystem Symfony boasts a wide array of reusable components and bundles, while Sylius offers numerous plugins to extend functionality. Together, they provide everything you need for building a full-fledged e-commerce platform. 6. Open Source Community Both Symfony and Sylius are open source, backed by active communities. This ensures continuous updates, security patches, and a wealth of learning resources. Real-World Applications Businesses across various industries use Symfony and Sylius to power their e-commerce operations. Here are some scenarios where this combination shines: B2C Stores: Create user-friendly interfaces for retail customers. B2B Platforms: Handle complex workflows like bulk ordering and role-based access control. Headless E-commerce: Use Sylius as the backend while delivering a cutting-edge frontend experience. Marketplaces: Build multi-vendor platforms with features like product listing and commission management. Getting Started To build an e-commerce site using Symfony and Sylius: Set Up Symfony and Sylius: Install Symfony and Sylius using Composer. Configure Your Platform: Use Sylius’s admin panel to manage products, categories, and orders. Customize to Your Needs: Leverage Symfony’s bundles and Sylius plugins to add unique features. Optimize Performance: Use Symfony’s caching and optimization tools to ensure a smooth shopping experience. Conclusion Symfony and Sylius are a match made in heaven for developers seeking a powerful, flexible, and scalable solution for e-commerce. Whether you’re starting a small online shop or scaling an enterprise platform, this combination provides all the tools and features you need to succeed. Embrace Symfony and Sylius to build the e-commerce platform of your dreams!
Symfony Development

Why Use Coding Standards in Web Development: A Symfony Perspective

Introduction In the fast-paced world of web development, adhering to coding standards is not just a best practice—it’s a necessity. For Symfony developers, following coding standards can significantly improve code quality, maintainability, and collaboration. In this blog post, we’ll explore why coding standards matter, their benefits, and how Symfony facilitates their implementation. What Are Coding Standards? Coding standards are a set of guidelines and rules that define how code should be written, structured, and formatted. These standards promote consistency and readability across projects, ensuring that all developers work in harmony, regardless of individual coding styles. For Symfony, coding standards are often based on PSR (PHP Standards Recommendations), which provide a solid foundation for creating clean and organized PHP code. Why Are Coding Standards Important in Symfony? Improved Readability Adhering to a consistent coding style makes your Symfony code easier to read and understand. Whether it’s a controller, service, or template, a standardized approach ensures clarity for all team members. Ease of Collaboration In team environments, developers often work on shared codebases. Coding standards minimize confusion, making it easier for developers to jump into unfamiliar parts of the code. Reduced Errors Consistent coding reduces the chances of errors and bugs, as well-structured code is easier to debug and test. For instance, following Symfony’s recommended folder structure and naming conventions can prevent issues related to class autoloading. Better Maintainability Symfony projects often evolve over time. Adhering to coding standards ensures that code remains maintainable, even as new features are added or team members change. Improved Performance with Tools Coding standards enable the use of tools like linters, code analyzers, and auto-formatters. For Symfony, tools like PHP-CS-Fixer and PHPStan help developers enforce and check adherence to coding standards efficiently. How Symfony Supports Coding Standards Symfony, being a robust PHP framework, encourages the use of coding standards through built-in features and community tools: PSR Compliance Symfony aligns with PSR standards, such as PSR-1 (Basic Coding Standards) and PSR-12 (Extended Coding Style Guide). This ensures that Symfony code is consistent with the broader PHP ecosystem. Symfony Coding Standards The Symfony documentation provides detailed guidelines for writing clean and efficient code, including naming conventions, indentation, and file structure. Integration with Tools Symfony projects seamlessly integrate with tools like: PHP-CS-Fixer: Automatically fixes coding style issues. PHPStan: Ensures static analysis to catch bugs early. Composer Scripts: Automate checks and formatting tasks as part of your development workflow. Community Contributions Symfony has a large and active community that adheres to coding standards, making it easier to find resources, examples, and support for your projects. How to Implement Coding Standards in a Symfony Project Define Your Standards Decide whether to follow Symfony’s coding standards or customize them based on your project needs. Use tools like .php-cs-fixer.dist.php to define your rules. Automate with Tools Set up tools like PHP-CS-Fixer or integrate coding standards checks into your CI/CD pipeline. Educate Your Team Share coding standards documentation with your team and ensure that everyone understands and follows the guidelines. Regular Code Reviews Conduct code reviews to catch deviations and encourage adherence to standards. Conclusion Using coding standards in web development, particularly in Symfony projects, is essential for creating clean, maintainable, and collaborative codebases. By adhering to these standards, you can enhance readability, reduce bugs, and ensure long-term project success. Leverage Symfony’s built-in features and community tools to implement and enforce coding standards effectively.
Symfony Development

Why Symfony is the Best PHP Framework for Modern Web Development

Introduction Symfony is one of the most popular and powerful PHP frameworks, used by developers worldwide to build robust, scalable, and maintainable web applications. Whether you are building a simple blog or a complex enterprise application, Symfony provides the tools, flexibility, and reliability you need. In this blog, we’ll explore why Symfony stands out as the best PHP framework, highlighting its key features, benefits, and how it compares to other frameworks. What is Symfony? Symfony is an open-source PHP framework based on the Model-View-Controller (MVC) architecture. Released in 2005, Symfony is maintained by SensioLabs and a thriving community of developers. Over the years, it has established itself as a go-to framework for developers seeking high performance and scalability. Why Choose Symfony? Here are the top reasons why Symfony is considered the best PHP framework: 1. Flexibility with Bundles and Components Symfony’s modular architecture allows developers to use only what they need. It consists of reusable components and bundles that can be integrated into other frameworks or standalone projects. With over 50 standalone components like the HTTP Foundation, Console, and Dependency Injection, Symfony is ideal for both microservices and full-stack applications. 2. Strong Community and Long-Term Support (LTS) Symfony boasts a strong developer community that actively contributes to its growth. It also offers long-term support (LTS) for major versions, ensuring stability and security for enterprise applications. 3. High Performance and Scalability Symfony’s optimized codebase ensures that applications run efficiently even under high traffic. Its robust caching system, combined with tools like Doctrine ORM, makes it highly scalable. 4. Best Practices and Code Standards Symfony enforces coding best practices and adheres to the PSR standards, ensuring clean, readable, and maintainable code. This makes it easier for teams to collaborate and onboard new developers. 5. Advanced Security Features Symfony provides out-of-the-box security features, such as user authentication, role-based access control (RBAC), and protection against common vulnerabilities like XSS, CSRF, and SQL Injection. 6. Built-In Tools for Faster Development Symfony includes powerful tools like: Symfony Profiler: Debugging and performance monitoring. MakerBundle: Automates repetitive tasks like generating controllers, entities, and forms. Flex: Simplifies package installation and configuration. These tools save time and boost developer productivity. 7. Vibrant Ecosystem Symfony integrates seamlessly with modern technologies like Docker, Kubernetes, and API platforms. It also powers major PHP frameworks like Laravel, which is built on Symfony components. How Symfony Compares to Other PHP Frameworks Let’s compare Symfony with other popular PHP frameworks: FeatureSymfonyLaravelCodeIgniterModularityHighly ModularLess ModularLimited ModularityPerformanceHighMediumMediumScalabilityExcellentGoodLimitedSecurityAdvancedModerateBasicCommunity SupportStrongStrongModerate Symfony stands out for its modularity, performance, and focus on enterprise-grade applications. Real-World Use Cases Symfony is trusted by top companies and projects worldwide, including: Drupal: A leading content management system. Magento 2: An e-commerce platform. BlaBlaCar: A global carpooling service. Conclusion Symfony is the ideal PHP framework for developers who value flexibility, performance, and maintainability. Its advanced features, adherence to best practices, and vibrant community make it a top choice for building modern web applications.
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
×