为什么我可以从命令行 find/save 而不是在我的 Symfony 应用程序中?
Why I can find/save from command line but not in my Symfony app?
为了我的个人发展,我尝试使用这个 repo https://github.com/dunglas/symfony-docker 作为 Docker 基础来创建一个 PHP 8/Symfony 5 环境。
我可以在 https://localhost 上启动我的应用程序,更新我的项目会反映在浏览器上。但是我对 Doctrine 有一个奇怪的看法。实际上,我可以使用 Symfony 命令 bin/console doctrine:schema:update --force
更新我的数据库模式,使用 Doctrine Migrations 或也使用命令插入数据。但是,当我尝试在我的 Symfony 应用程序中 find/save 数据时,我发现没有结果并且 create/update.
上没有数据插入
这是我的 docker-compose.yml(几乎与 repo 相同,只有数据库 > 卷发生变化):
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 ###
还有我的 env 文件(同样几乎与原始文件相同):
# 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:db_password@127.0.0.1:3306/db_name?serverVersion=5.7"
DATABASE_URL="postgresql://symfony:ChangeMe@127.0.0.1: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 ###
感谢您的帮助
编辑:
这是我的浏览器应用请求测试代码:
<?php
namespace App\Controller;
use App\Entity\Category;
use App\Entity\Product;
use App\Finder\ProductFinder;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[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',
]);
}
}
这是我的配置原则:
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: 'App\Entity'
alias: App
这是从命令行调用的代码的一部分及其工作位置:
<?php
namespace App\Message\Handler;
use App\Entity\Category;
use App\Entity\Image;
use App\Entity\Product;
use App\Message\SynchronizeProductMessage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
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);
}
}
}
持久化后必须在 Doctrine 实体管理器上调用 flush:
$this->entityManager->flush();
好的,我终于找到了解决方案。我更改了未直接反映在 Docker build 中的 .env 文件,因为我必须这样设置它:
POSTGRES_DB=my_db_name docker-compose up -d --build
或者替换配置文件中的数据库默认名称。
感谢您的帮助:)
为了我的个人发展,我尝试使用这个 repo https://github.com/dunglas/symfony-docker 作为 Docker 基础来创建一个 PHP 8/Symfony 5 环境。
我可以在 https://localhost 上启动我的应用程序,更新我的项目会反映在浏览器上。但是我对 Doctrine 有一个奇怪的看法。实际上,我可以使用 Symfony 命令 bin/console doctrine:schema:update --force
更新我的数据库模式,使用 Doctrine Migrations 或也使用命令插入数据。但是,当我尝试在我的 Symfony 应用程序中 find/save 数据时,我发现没有结果并且 create/update.
这是我的 docker-compose.yml(几乎与 repo 相同,只有数据库 > 卷发生变化):
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 ###
还有我的 env 文件(同样几乎与原始文件相同):
# 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:db_password@127.0.0.1:3306/db_name?serverVersion=5.7"
DATABASE_URL="postgresql://symfony:ChangeMe@127.0.0.1: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 ###
感谢您的帮助
编辑:
这是我的浏览器应用请求测试代码:
<?php
namespace App\Controller;
use App\Entity\Category;
use App\Entity\Product;
use App\Finder\ProductFinder;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[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',
]);
}
}
这是我的配置原则:
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: 'App\Entity'
alias: App
这是从命令行调用的代码的一部分及其工作位置:
<?php
namespace App\Message\Handler;
use App\Entity\Category;
use App\Entity\Image;
use App\Entity\Product;
use App\Message\SynchronizeProductMessage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
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);
}
}
}
持久化后必须在 Doctrine 实体管理器上调用 flush:
$this->entityManager->flush();
好的,我终于找到了解决方案。我更改了未直接反映在 Docker build 中的 .env 文件,因为我必须这样设置它:
POSTGRES_DB=my_db_name docker-compose up -d --build
或者替换配置文件中的数据库默认名称。
感谢您的帮助:)