I have defined two different entity managers in doctrine.yaml
entity_managers:
EM1:
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
App\EM1:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/BC1/Domain/Entity'
prefix: 'BC1\Domain\Entity'
alias: App\EM1
EM2:
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
App\EM2:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/BC2/Domain/Entity'
prefix: 'BC2\Domain\Entity'
alias: App\EM2
and I am injecting a Doctrine EntityManagerInterface in my service:
service.yaml
DoctrineRepository:
class: BC\Infrastructure\Persistence\DoctrineRepository
arguments:
- "#Doctrine\\ORM\\EntityManagerInterface"
DoctrineRepository.php
public function __construct(
EntityManagerInterface $client
) {
$this->entityManager = $client;
}
I want to be able to select which Entity Manager previously defined (EM1, EM2) I want to use when using DoctrineRepository. Idealy it would be something like:
$this->entityManager->useEntityManager('EM2');
Do I need to inject another service instead of a Doctrine\ORM\EntityManagerInterface? I have debugged the entity managers load and I have found that it automatically assigns the first one when generating cache:
cache/dev/getDoctrineRepositoryService.php:
return $this->privates['DoctrineRepository'] = new BC\Infrastructure\Persistence\DoctrineRepository(($this->services['doctrine.orm.EM1_entity_manager'] ?? $this->load('getDoctrine_Orm_EM1EntityManagerService.php')));
Any help would be apreciated, thanks.
I think I found another solution. Instead of injecting an EntityManagerInterface, I have injected #Doctrine itself (it injects a Doctrine\Bundle\DoctrineBundle\Registry object), and from that object you can do a $object->getManager($manager) so select the entity manager you want
Since you have two services that implements the same interface you need to help autowiring of Symfony.
Like explained in the docs:
you can create a normal alias from the TransformerInterface interface to Rot13Transformer, and then create a named autowiring alias from a special string containing the interface followed by a variable name matching the one you use when doing the injection
In your case
# the ``App\EM2`` service will be
# injected when an ``Doctrine\ORM\EntityManagerInterface``
# type-hint for a ``$em2Manager`` argument is detected.
Doctrine\ORM\EntityManagerInterface $em2Manager: '#App\EM2'
# If the argument used for injection does not match, but the
# type-hint still matches, the ``Doctrine\ORM\EntityManagerInterface``
# service will be injected.
Doctrine\ORM\EntityManagerInterface: '#App\EM1'
Related
I'm trying to work with kayue/KayueWordpressBundle installed with composer as composer require kayue/kayue-wordpress-bundle in my Symfony 4.4.1 project but I'm unable to.
This is what I'm trying to do:
<?php
namespace App\Service\WordPress;
use Doctrine\ORM\EntityManagerInterface;
use Kayue\WordpressBundle\Entity\Post;
class PostCollection
{
protected $postRepository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->postRepository = $entityManager->getRepository(Post::class);
}
}
The error I get:
The class 'Kayue\WordpressBundle\Entity\Post' was not found in the chain configured namespaces App\Entity
At first I blamed my dual-database configuration (Symfony is on a different DB from Wordpress) but then I put the DBs together and the issue persists:
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
# Only needed for MySQL (ignored otherwise)
charset: utf8mb4
default_table_options:
collate: utf8mb4_unicode_ci
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
I've been fiddling for the past 2hrs, but now I'm fresh out of ideas. I wonder if ANYONE actually got this to work with Symfony 4.
Thanks!
Edit: other tries:
Direct post injection:
use Kayue\WordpressBundle\Entity\Post;
public function index(Post $post){}
Result:
Cannot autowire argument $post of "App\Controller\IndexController::index()": it references class "Kayue\WordpressBundle\Entity\Post" but no such service exists.
As per documentation: outdated Symfony 2 way
$repo = $this->get('kayue_wordpress')->getManager()->getRepository('KayueWordpressBundle:Post');
Result:
Service "kayue_wordpress" not found: even though it exists in the app's container, the container inside "App\Controller\IndexController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead.
The "best way" to do this would actually be:
public function index(EntityManagerInterface $entityManager)
{
$entityManager->getRepository('KayueWordpressBundle:Post');
}
Result:
The class 'Kayue\WordpressBundle\Entity\Post' was not found in the chain configured namespaces App\Entity
Although you found a solution to this, there is a chain of issues I would like to explain.
The error
The class 'Kayue\WordpressBundle\Entity\Post' was not found in the chain configured namespaces App\Entity
means that in the entity manager provided, whose config is defined at:
orm:
...
mappings:
App:
...
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
the entity type Kayue\WordpressBundle\Entity\Post was not found.
Usually this type of error is solved by:
include the path Kayue\WordpressBundle\Entity in the entity manager or
use another entity manager which includes this path
In your case the default entity manager is autowired, based on the service alias of Doctrine\ORM\EntityManagerInterface as explained here. The alias is defined in the doctrine bundle `s config which points to the default doctrine entity manager.
You want to use Kayue\WordpressBundle `s entity manager, not the default one.
Solution
To solve this you can
1) Bind Arguments By type, as you find out, creating an alias of Kayue\WordpressBundle\Wordpress\ManagerRegistry to the service kayue_wordpress, as:
services:
# pass this service for any ManagerRegistry type-hint for any
# service that's defined in this file
Kayue\WordpressBundle\Wordpress\ManagerRegistry: '#kayue_wordpress'
or
2) use Binding Arguments by Name, in this case the "$wpManagerRegistry", as:
services:
# default configuration for services in *this* file
_defaults:
...
bind:
$wpManagerRegistry: '#kayue_wordpress'
and then
public function index($wpManagerRegistry)
{
$postRepository = $wpManagerRegistry->getManager()->getRepository('KayueWordpressBundle:Post');
so that any argument with name "$wpManagerRegistry" is autowired to this service.
References
The Symfony 3.3 DI Container Changes Explained (autowiring, _defaults, etc)
My collegue found a solution. You must configure the autowire like this:
// config/packages/kayue_wordpress.yaml
services:
Kayue\WordpressBundle\Wordpress\ManagerRegistry: '#kayue_wordpress'
After that, you can autowire:
use Kayue\WordpressBundle\Wordpress\ManagerRegistry;
public function __construct(ManagerRegistry $wpManagerRegistry)
{
$this->wpPostRepository = $wpManagerRegistry->getManager()->getRepository('KayueWordpressBundle:Post');
}
public function getPosts()
{
$post = $this->wpPostRepository->findOneBy(array(
'slug' => 'hello-world',
'type' => 'post',
'status' => 'publish',
));
}
I'm using Symfony 4.3.8 and I can't find any information about thoses deprecations :
User Deprecated: Creating Doctrine\ORM\Mapping\UnderscoreNamingStrategy without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.
Creating Doctrine\ORM\Mapping\UnderscoreNamingStrategy without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.
I searched in stacktrace and found this :
class UnderscoreNamingStrategy implements NamingStrategy
{
private const DEFAULT_PATTERN = '/(?<=[a-z])([A-Z])/';
private const NUMBER_AWARE_PATTERN = '/(?<=[a-z0-9])([A-Z])/';
/**
* Underscore naming strategy construct.
*
* #param int $case CASE_LOWER | CASE_UPPER
*/
public function __construct($case = CASE_LOWER, bool $numberAware = false)
{
if (! $numberAware) {
#trigger_error(
'Creating ' . self::class . ' without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.',
E_USER_DEPRECATED
);
}
$this->case = $case;
$this->pattern = $numberAware ? self::NUMBER_AWARE_PATTERN : self::DEFAULT_PATTERN;
}
In this class, the constructor is always called without params, so $numberAware is always false.
This class is called in file which has been auto generated by the Symfony Dependency Injection, so I can't "edit" it ...
I thought maybe it was in doctrine.yaml :
doctrine:
orm:
auto_generate_proxy_classes: true
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
App:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
But I have not found any option to allow the number aware :(
In most cases I would just answer this sort of question with a comment but I suspect other developers might run into this issue. I poked around a bit and could not find any explicit documentation on this issue. Perhaps because the DoctrineBundle is under the control of the Doctrine folks and not the Symfony developers. Or maybe I am just a bad searcher.
In any event, between 4.3 and 4.4 the service name for the underscore naming strategy was changed.
# doctrine.yaml
orm:
# 4.3
naming_strategy: doctrine.orm.naming_strategy.underscore
# 4.4
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
And a deprecated message was added to warn developers to change the name. Would have been nice if the message was just a tiny bit more explicit but oh well.
So if you are upgrading an existing app to 4.4 and beyond then you will probably need to manually edit your doctrine.yaml file to make the depreciation message go away.
Some more info (thanks #janh) on why the change was made:
https://github.com/doctrine/orm/blob/2.8.x/UPGRADE.md#deprecated-number-unaware-doctrineormmappingunderscorenamingstrategy
https://github.com/doctrine/orm/issues/7855
Still not really clear on why "they" chose to do things this way but oh well.
You probably want to run "bin/console doctrine:schema:update --dump-sql" just to see if this impacts your database column names and adjust accordingly. The changes has been out for several weeks now and there does not seem to be many howls of outrage over the change so I guess most column names don't have embedded numbers. So far at least.
For those who works with symfony4.3 and still want this warning disapear you can add add new new service defintion in service.yaml
custom_doctrine_orm_naming_strategy_underscore:
class: Doctrine\ORM\Mapping\UnderscoreNamingStrategy
arguments:
- 0
- true
and change the configuration of doctrine.yaml like this:
orm:
naming_strategy: custom_doctrine_orm_naming_strategy_underscore
before going straight forward committing this change I would suggest you to verify that passing true to the Doctrine\ORM\Mapping\UnderscoreNamingStrategy doesn't affect the expected behavior of your code.
// class UnderscoreNamingStrategy
/**
* Underscore naming strategy construct.
*
* #param int $case CASE_LOWER | CASE_UPPER
*/
public function __construct($case = CASE_LOWER, bool $numberAware = false)
{
if (! $numberAware) {
#trigger_error(
'Creating ' . self::class . ' without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.',
E_USER_DEPRECATED
);
}
$this->case = $case;
$this->pattern = $numberAware ? self::NUMBER_AWARE_PATTERN : self::DEFAULT_PATTERN;
}
Quick hint:
passing true to the c'tor will make the class use the NUMBER_AWARE_PATTERN instead of the DEFAULT_PATTERN
private const DEFAULT_PATTERN = '/(?<=[a-z])([A-Z])/';
private const NUMBER_AWARE_PATTERN = '/(?<=[a-z0-9])([A-Z])/';
I have to bind parameters with different values in different environments, and having problems with this.
I was trying this:
# config/services.yaml
services:
_defaults:
bind:
$param: 'param for PROD'
# config/services_dev.yaml
services:
_defaults:
bind:
$param: 'param for DEV'
# src/Controller/SomeController.php
class MyController extends AbstractController
{
public function example($param)
{
echo $param;
}
}
But it forces me to have all the services defined in both of services.yaml and services_dev.yaml files, otherwise it does not work.
I would like to have a services.yaml shared for any environment, and only override the custom services/bindings etc, not have two identical files with all services listed in them for changing one binding value.
The real problem is that I have to create two http clients (real and a dummy) with same interface, in production load the real one, and in development load the dummy, Symfony 4-s autowiring allows me to inject the interface in a controller and choose which client to use in binding:
# config/services.yaml
services:
_defaults:
bind:
'ClientInterface': '#real_client'
# More services here...
# config/services_dev.yaml
services:
_defaults:
bind:
'ClientInterface': '#dummy_client'
# Here I don't want to have another copy of the services,
# but it does not work without them
# Controller
public function someMethod(ClientInterface $client)
{
// ...
}
In Symfony 2 I was able to extend services.yml and in services_dev.yml only define the specific values I wanted to override/add, but in Symfony 4 services_dev.yaml can not use services from services.yaml and I have to keep my services identical in two different files which is pain.
Anny suggestions?
Thank you.
I'm updating the post again with a real example:
services.yaml
# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: 'en'
app.access_token: '%env(string:APP_ACCESS_TOKEN)%'
app.aws_version: '%env(string:AWS_VERSION)%'
app.aws_profile: '%env(string:AWS_PROFILE)%'
app.aws_region: '%env(string:AWS_REGION)%'
app.aws_queue_url_creation: '%env(string:AWS_QUEUE_URL_CAMPAIGN_CREATION)%'
app.aws_queue_url_edition: '%env(string:AWS_QUEUE_URL_CAMPAIGN_EDITION)%'
app.redis_host: '%env(string:REDIS_HOST)%'
app.redis_port: '%env(string:REDIS_PORT)%'
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
bind:
App\Service\MessageSenderServiceInterface: '#App\Service\MessageSenderSqsService'
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
# Authenticators
App\Security\ApiKeyAuthenticator:
arguments:
- "%app.access_token%"
# Clients
App\Client\AwsSqsClient:
arguments:
- "%app.aws_version%"
- "%app.aws_profile%"
- "%app.aws_region%"
App\Client\RedisClient:
arguments:
- "%app.redis_host%"
- "%app.redis_port%"
# Services
App\Service\MessageSenderSqsService:
arguments:
- '#App\Client\AwsSqsClient'
- '#App\Client\RedisClient'
- "%app.aws_queue_url_creation%"
- "%app.aws_queue_url_edition%"
App\Service\MessageSenderRedisService:
arguments:
- '#App\Client\RedisClient'
services_dev.yaml
imports:
- { resource: services.yaml }
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
bind:
App\Service\MessageSenderServiceInterface: '#App\Service\MessageSenderRedisService'
Controller.php
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class TestController extends AbstractController
{
/**
* #Route("/api/dummy")
*/
public function dummyEndpoint(MessageSenderServiceInterface $messageSender)
{
echo get_class($messageSender); exit;
}
}
And the echo from controller for both envs (prod and dev) is
App\Service\MessageSenderSqsService
But if I copy whole node "services" form services.yaml to services_dev.yaml and only change the binding config, it works fine and says that the injected class is:
App\Service\MessageSenderRedisService
I've just noticed that if I don't touch the "_defaults" node, it works as expected, the problems start only when I want to override the _defaults node of services...
You can define parameters in parameters section of config.yml and overwrite this parameters in config_dev.yml.
# config.yml
imports:
# ...
parameters:
parameter_1: value 1
parameter_2: value 2
# ...
framework:
# ...
# config_dev.yml
imports:
# ...
parameters:
parameter_1: dev value 1
# ...
framework:
# ...
This parameters can be used used in service.yml as:
# service.yml
services:
_defaults:
bind:
$param: '%parameter_1%'
Finally the problem was only in overriding the "_defaults" node (which I was touching in order to have different "bind" configs in the project).
Extending services.yaml without overriding _defaults, everything works as expected. And the solution is to have different configuration for services with their bindings by environment, and have "_defaults" only in services.yaml.
If we override the "_defaults" in other files, we'll have to redefine all the services too.
Thanks everyone for help.
You have some options:
1.Don't use bind and write different service configs for different environments
# services.yaml
App\Controller:
arguments:
- "#client"
# services_dev.yaml
App\Controller:
arguments:
- "#dummy_client"
2.Use bind and create service alias in each environment's services.yaml:
# services.yaml
services:
some.client:
alias: "#client"
# services_dev.yaml
services:
some.client:
alias: "#dummy_client"
3.Just configure only one ClientInterface service per environment:
# services.yaml
App\ClientInterface:
class: App\RealClient
# services_dev.yaml
App\ClientInterface:
class: App\DummyClient
4.Use factory which will create this client depends on environment (but this is not very good practice as for me)
# services.yaml
App\ClientInterface:
factory: ["#App\ClientFactory", create]
arguments:
- '%kernel.environment%'
class ClientFactory
{
public function create(string $env): ClientInterface
{
if ($env === 'dev') {
return new DummyClient();
} else {
return new Client();
}
}
}
5.In your case, when you have so much services and you want to inject same service in all of them, you can use option #3 or you can create one interface for all of them and use _instanceof:
# services.yaml
_instanceof:
App\SomeCommonInterface:
calls:
- method: setSomeService # interface's method
arguments:
- '#service'
# services_dev.yaml
_instanceof:
App\SomeCommonInterface:
calls:
- method: setSomeService
arguments:
- '#dummy_service'
I'm trying to refactor some Symfony 3 code to Symfony 4.
I am getting the following error when attempting to log:
The "monolog.logger.db" service or alias has been removed or inlined
when the container was compiled. You should either make it public, or
stop using the conta iner directly and use dependency injection
instead.
My logging code:
$logger = $container->get('monolog.logger.db');
$logger->info('Import command triggered');
Monolog config:
monolog:
channels: ['db']
handlers:
db:
channels: ['db']
type: service
id: app.monolog.db_handler
app.monolog.db_handler config (Note, I tried public: true here and it had no affect:
app.monolog.db_handler:
class: App\Util\MonologDBHandler
arguments: ['#doctrine.orm.entity_manager']
How can I get this wired up correctly in Symfony 4?
By default all services in Symfony 4 are private (and is the recommended pratice) so you need to "inject" in each Controller each needed service (personally I use a custom CommonControllerServiceClass).
You can also create a public service "alias" to continue accessing the service as you did, but it's not the best pratice to follow (also because I guess you will have many other services to fix).
mylogger.db:
alias: monolog.logger.db
public: true
then you can get the service from the container:
$logger = $container->get('mylogger.db');
Alister's answer is a good start, but you can utilise service arguments binding instead of creating a new service for each logger:
services:
_defaults:
autowire: true
bind:
$databaseLogger: '#monolog.logger.db'
Then just change the argument name in your class:
// in App\Util\MonologDBHandler.php
use Psr\Log\LoggerInterface;
public function __construct(LoggerInterface $databaseLogger = null) {...}
It appears that App\Util\MonologDBHandler may be the only thing that is actively using monolog.logger.db - via a container->get('...') call. (If not, you will want to use this technique to tag the specific sort of logger into more services).
You would be better to allow the framework to build the app.monolog.db_handler service itself, and use the container to help to build it. Normally, to inject a logger service, you will just need to type-hint it:
// in App\Util\MonologDBHandler.php
use Psr\Log\LoggerInterface;
public function __construct(LoggerInterface $logger = null) {...}
However, that will, by default, setup with the default #logger, so you need to add an extra hint in the service definition of the handler that you want a different type of logger:
services:
App\Log\CustomLogger:
arguments: ['#logger']
tags:
- { name: monolog.logger, channel: db }
Now, the logger in CustomLogger should be what you had previously known as monolog.logger.db.
You can also alias a different interface (similar to how the LoggerInterface is aliased to inject '#logger') to the allow for the tagging.
I've created a bundle completely separate from the main app, so I install it via Composer.
This bundle requires some sort of configuration:
# app/config/config.yml
shq_mybundle:
node1:
node1_1:
...
node1_2:
...
node2:
node2_1:
...
node2_2:
...
My bundle also has a controller MyBundleAController and this controller has a ––construct() with this signature:
class MyBundleAController
{
public function __construct(EntityManagerInterface $entityManager, EventDispatcherInterface $eventDispatcher, array $config)
{
$this->entityManager = $entityManager;
$this->eventDispatcher = $eventDispatcher;
$this->config = $config;
}
}
My bundle also loads a services.yml file that uses autowiring to configure controllers:
services:
# default configuration for services in *this* file
_defaults:
# automatically injects dependencies in your services
autowire: true
# automatically registers your services as commands, event subscribers, etc.
autoconfigure: true
# this means you cannot fetch services directly from the container via $container->get()
# if you need to d
SerendipityHQ\Bundle\MyBundle\Controller\:
resource: '../../Controller/*'
public: false
tags: ['controller.service_arguments']
Obviously, the way MyBundleAController is configured throws an error, as the $config argument is unknown by the autowiring functionality that requires the argument be typehinted or explicitly set:
Cannot autowire service
"SerendipityHQ\Bundle\MyBundle\Controller\MyBundleAController":
argument "$config" of method "__construct()" must have a type-hint or
be given a value explicitly.
And here we arrive to my question: the $config parameter is the one that someone sets in its app/config/config.yml, so this one:
# app/config/config.yml
shq_mybundle:
node1:
node1_1:
...
node1_2:
...
node2:
node2_1:
...
node2_2:
...
How can I pass shq_mymodule configuration to the autowired controller?
In a first attempt, I've tried to do something like this
SerendipityHQ\Bundle\MyBundle\Controller\ConnectController:
arguments:
$config: "%shq_mybundle%"
But obviously this doesn't work.
To make it work I should do something like this in MyBundleExtension:
$container->setParameter('shq_mybundle', $config);
This way I transform it in a parameter accessible from the services.yml file that can use it to autowire the MyBundleAController controller.
But this seems to me like an hack: is there a more elegant way to do this?