skip to Main Content

For my personal development, I try using this repo https://github.com/dunglas/symfony-docker as Docker base to create a PHP 8/Symfony 5 environnement.

I could launch my App on https://localhost, updating my project is reflected on browser. But I got a weird thing with Doctrine. Actually, I could update my database schema using Symfony command bin/console doctrine:schema:update --force, using Doctrine Migrations or insert data using command too. But, when I try to find/save data within my Symfony app, there is no result when I find and no data insert on create/update.

Here is my docker-compose.yml (almost same as repo, only database > volumes change):

version: "3.4"

services:
  php:
    build:
      context: .
      target: symfony_php
      args:
        SYMFONY_VERSION: ${SYMFONY_VERSION:-}
        SKELETON: ${SKELETON:-symfony/skeleton}
        STABILITY: ${STABILITY:-stable}
    restart: unless-stopped
    volumes:
      - php_socket:/var/run/php
    healthcheck:
      interval: 10s
      timeout: 3s
      retries: 3
      start_period: 30s
    environment:
      # Run "composer require symfony/orm-pack" to install and configure Doctrine ORM
      DATABASE_URL: postgresql://${POSTGRES_USER:-symfony}:${POSTGRES_PASSWORD:-ChangeMe}@database:5432/${POSTGRES_DB:-app}?serverVersion=${POSTGRES_VERSION:-13}
      # Run "composer require symfony/mercure-bundle" to install and configure the Mercure integration
      MERCURE_URL: ${CADDY_MERCURE_URL:-http://caddy/.well-known/mercure}
      MERCURE_PUBLIC_URL: https://${SERVER_NAME:-localhost}/.well-known/mercure
      MERCURE_JWT_SECRET: ${CADDY_MERCURE_JWT_SECRET:-!ChangeMe!}

  caddy:
    build:
      context: .
      target: symfony_caddy
    depends_on:
      - php
    environment:
      SERVER_NAME: ${SERVER_NAME:-localhost, caddy:80}
      MERCURE_PUBLISHER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET:-!ChangeMe!}
      MERCURE_SUBSCRIBER_JWT_KEY: ${CADDY_MERCURE_JWT_SECRET:-!ChangeMe!}
    restart: unless-stopped
    volumes:
      - php_socket:/var/run/php
      - caddy_data:/data
      - caddy_config:/config
    ports:
      # HTTP
      - target: 80
        published: 80
        protocol: tcp
      # HTTPS
      - target: 443
        published: 443
        protocol: tcp
      # HTTP/3
      - target: 443
        published: 443
        protocol: udp

###> doctrine/doctrine-bundle ###
  database:
    image: postgres:${POSTGRES_VERSION:-13}-alpine
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-app}
      # You should definitely change the password in production
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-ChangeMe}
      POSTGRES_USER: ${POSTGRES_USER:-symfony}
    volumes:
      #- db-data:/var/lib/postgresql/data:rw
      # You may use a bind-mounted host directory instead, so that it is harder to accidentally remove the volume and lose all your data!
       - ./docker/db/data:/var/lib/postgresql/data:rw
###< doctrine/doctrine-bundle ###

volumes:
  php_socket:
  caddy_data:
  caddy_config:

###> doctrine/doctrine-bundle ###
  db-data:
###< doctrine/doctrine-bundle ###

And my env file (again almost, the same as original):

# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
#  * .env                contains default values for the environment variables needed by the app
#  * .env.local          uncommitted file with local overrides
#  * .env.$APP_ENV       committed environment-specific defaults
#  * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration

###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=a89e71950291aa659ff013c37031a35b
###< symfony/framework-bundle ###

###> symfony/mailer ###
# MAILER_DSN=smtp://localhost
###< symfony/mailer ###

###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
# DATABASE_URL="mysql://db_user:[email protected]:3306/db_name?serverVersion=5.7"
DATABASE_URL="postgresql://symfony:[email protected]:52399/drop_shipping_builder?serverVersion=13&charset=utf8"
###< doctrine/doctrine-bundle ###

###> symfony/messenger ###
# Choose one of the transports below
MESSENGER_FAILED_TRANSPORT_DSN=doctrine://default?queue_name=failed
MESSENGER_TRANSPORT_DSN=doctrine://default
# MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages
# MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
###< symfony/messenger ###

Thanks for your help

EDIT:

Here is my test code for browser app request:

<?php

namespace AppController;

use AppEntityCategory;
use AppEntityProduct;
use AppFinderProductFinder;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;

#[Route('/front')]
class FrontProductController extends AbstractController
{
    #[Route('/product', name: 'front_product')]
    public function index(ProductFinder $finder, Request $request): Response
    {

        $category = new Category();
        $category->setName('enpme')
            ->setKey('pzafn');

        $this->getDoctrine()->getManager()->persist($category);
        $this->getDoctrine()->getManager()->flush();


        $this->getDoctrine()->getRepository(Product::class)->findAll();

        return $this->render('front_product/index.html.twig', [
            'controller_name' => 'FrontProductController',
        ]);
    }
}

Here is my config Doctrine:

doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'

        # IMPORTANT: You MUST configure your server version,
        # either here or in the DATABASE_URL env var (see .env file)
        #server_version: '13'
    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'AppEntity'
                alias: App

And here is a part of code that is called from command line and where it works:

<?php

namespace AppMessageHandler;

use AppEntityCategory;
use AppEntityImage;
use AppEntityProduct;
use AppMessageSynchronizeProductMessage;
use DoctrineORMEntityManagerInterface;
use SymfonyComponentMessengerHandlerMessageHandlerInterface;
use SymfonyComponentOptionsResolverOptionsResolver;

class SynchronizeProductMessageHandler implements MessageHandlerInterface
{
    protected EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function __invoke(SynchronizeProductMessage $message)
    {
        $rawProduct = $this->validate($message->getRawProduct());
        $product = ($this->getProduct($rawProduct))
            ->setPrice($rawProduct[Product::RAW_KEY_PRICE])
            ->setDescription($rawProduct[Product::RAW_KEY_DESCRIPTION])
            ->setDescription($rawProduct[Product::RAW_KEY_TECHNICAL_DESCRIPTION])
        ;

        $this->manageCategory($product, $rawProduct);
        $this->manageImages($product, $rawProduct);

        $this->entityManager->persist($product);
        $this->entityManager->flush();
    }

    protected function validate(array $rawProduct): array
    {
        $optionResolver = new OptionsResolver();
        $optionResolver->setRequired([
            Product::RAW_KEY_TARGET_ID,
            Product::RAW_KEY_SERVICE_PROVIDER_NAME,
            Product::RAW_KEY_NAME,
            Product::RAW_KEY_PRICE,
            Product::RAW_KEY_DESCRIPTION,
            Product::RAW_KEY_TECHNICAL_DESCRIPTION,
            Product::RAW_KEY_IMAGES,
            Product::RAW_KEY_CATEGORY,
        ]);

        return $optionResolver->resolve($rawProduct);
    }

    protected function validateImage(array $rawImage): array
    {
        $optionResolver = new OptionsResolver();
        $optionResolver->setRequired([
            Image::RAW_KEY_NAME,
            Image::RAW_KEY_PATH,
            Image::RAW_KEY_WIDTH,
            Image::RAW_KEY_HEIGHT,
        ]);

        return $optionResolver->resolve($rawImage);
    }

    protected function validateCategory(array $rawImage): array
    {
        $optionResolver = new OptionsResolver();
        $optionResolver->setRequired([
            Category::RAW_KEY_NAME,
            Category::RAW_KEY_KEY,
            Category::RAW_KEY_PARENT_KEY,
        ])->setDefault(Category::RAW_KEY_PARENT_KEY, null);

        return $optionResolver->resolve($rawImage);
    }

    protected function getProduct(array $rawProduct): Product
    {
        $product = $this->entityManager->getRepository(Product::class)->findByServiceProviderNameAndName(
            $rawProduct[Product::RAW_KEY_SERVICE_PROVIDER_NAME],
            $rawProduct[Product::RAW_KEY_NAME]
        );

        if (!$product instanceof Product) {
            $product = (new Product())
                ->setTargetId($rawProduct[Product::RAW_KEY_TARGET_ID])
                ->setName($rawProduct[Product::RAW_KEY_NAME])
                ->setServiceProviderName($rawProduct[Product::RAW_KEY_SERVICE_PROVIDER_NAME])
            ;
        }

        return $product;
    }

    public function manageCategory(Product $product, array $rawProduct): void
    {
        if (empty($rawProduct[Product::RAW_KEY_CATEGORY])) {
            return;
        }

        $rawCategory = $this->validateCategory($rawProduct[Product::RAW_KEY_CATEGORY]);
        $category = $this->entityManager->getRepository(Category::class)->findOneBy([
            'key' => $rawCategory[Category::RAW_KEY_KEY],
        ]);

        if (!$category instanceof Category) {
            $category = (new Category())->setKey($rawCategory[Category::RAW_KEY_KEY]);

            $parentCategory = $this->entityManager->getRepository(Category::class)->findOneBy([
                'key' => $rawCategory[Category::RAW_KEY_PARENT_KEY],
            ]);

            if ($parentCategory instanceof Category) {
                $category->setParent($parentCategory);
            }
        }

        $category->setName($rawCategory[Category::RAW_KEY_NAME]);
        $this->entityManager->persist($category);
        $product->setCategory($category);
    }

    public function manageImages(Product $product, array $rawProduct): void
    {
        foreach ($product->getImages() as $image) {
            $product->removeImage($image);
            $this->entityManager->remove($image);
        }

        foreach ($rawProduct[Product::RAW_KEY_IMAGES] as $rawImage) {
            $rawImageValidated = $this->validateImage($rawImage);
            $image = (new Image())
                ->setIsExternal(true)
                ->setName($rawImageValidated[Image::RAW_KEY_NAME])
                ->setPath($rawImageValidated[Image::RAW_KEY_PATH])
                ->setWidth((int) $rawImageValidated[Image::RAW_KEY_WIDTH])
                ->setHeight((int) $rawImageValidated[Image::RAW_KEY_HEIGHT])
            ;

            $this->entityManager->persist($image);
            $product->addImage($image);
        }
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    Ok I finally found the solution. I change the .env file that is not directly reflected in Docker build because I have to set it like this:

    POSTGRES_DB=my_db_name docker-compose up -d --build
    

    Or replace the DB default name inside config file.

    Thanks for your help :)


  2. You must call flush on the Doctrine entity manager after a persist:

    $this->entityManager->flush();
    

    Have a look at the documentation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search