I have setup a Custom Authenticator using guard and auto wired the service. This is tested and works fine with just MySQL configured.
I have now specified a second database connection (oracle), but Symfony will now not allow autowiring in my service configuration, because it does not know which database connection to use when injecting EntityManager in to the custom Authenticator class.
Any idea how I can Configure the Dependency Injection to use a specific database connection so I can continue to use AutoWire.
Unable to autowire argument of type "Doctrine\ORM\EntityManager" for the service "user.security.login_form_authenticator". Multiple services exist for this class (doctrine.orm.prism_entity_manager, doctrine.orm.baan_entity_manager).
Here is my Doctrine config in config.yml
doctrine:
dbal:
connections:
prism:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/../var/data/data.sqlite"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
#path: "%database_path%"
baan:
driver: oci8
host: "%baan_host%"
port: "%baan_port%"
dbname: "%baan_db_name%"
user: "%baan_user%"
password: "%baan_password%"
charset: AL32UTF8
orm:
default_entity_manager: prism
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
auto_mapping: true
prism:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: prism
mappings:
UserBundle:
type: annotation
baan:
connection: baan
mappings:
BaanBundle:
type: annotation
Here is the constructor in my Authenticator class
private $formFactory;
private $em;
private $router;
public function __construct(FormFactoryInterface $formFactory, EntityManager $em, RouterInterface $router)
{
$this->formFactory = $formFactory;
$this->em = $em;
$this->router = $router;
}
You can extend Doctrine's EntityManagerDecorator, which implements EntityManagerInterface and accepts an instance of EntityManager in its constructor.
First extend the EntityManagerDecorator class once for each of your connections.
namespace MyBundle\Service\Database;
use Doctrine\ORM\Decorator\EntityManagerDecorator;
class PrismEntityManager extends EntityManagerDecorator {}
class BaanEntityManager extends EntityManagerDecorator {}
Then in your service configuration, you need to manually wire these two services.
MyBundle\Service\Database\PrismEntityManager:
arguments:
$wrapped: '#doctrine.orm.prism_entity_manager'
MyBundle\Service\Database\BaanEntityManager:
arguments:
$wrapped: '#doctrine.orm.baan_entity_manager'
Now you just have to type-hint for one of these services.
public function __construct(FormFactoryInterface $formFactory, PrismEntityManager $em, RouterInterface $router)
{
$this->formFactory = $formFactory;
$this->em = $em;
$this->router = $router;
}
I don't know if i understood your question correctly or not but you can set different configurations for different database connection as below:
dbal:
default_connection: default
connections:
default:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
mapping_types:
enum: smallint
custom:
driver: pdo_mysql
host: '%database_host2%'
port: '%database_port2%'
dbname: '%database_name2%'
user: '%database_user2%'
password: '%database_password2%'
charset: UTF8
mapping_types:
enum: smallint
orm:
default_entity_manager: default
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
auto_mapping: true
default:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: default
mappings:
EntityBundle:
type: annotation
alias: DBAlias
custom:
naming_strategy: doctrine.orm.naming_strategy.underscore
connection: custom
mappings:
EntityBundle:
type: annotation
alias: DBAlias
Now you can passed your custom EntityManager using doctrine.orm.custom_entity_manager.
I think, I had the same issue with DBAL Connections as you have with EntityManager. I have solved this issue with some proxy class - described in this answer:
https://stackoverflow.com/a/46265170/6357312
Any question let me know.
Related
I'm working with multiple Entity Managers, followed Symfony doc from here,
but I want to use two entity manager for one dir.
It's not working properly in findAll or findOneBy query, it's showing the result for 'default' entity manager.
in config/packages/doctrine.yaml :
dbal:
# configure these for your database server
default_connection: default
connections:
default:
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
url: '%env(DATABASE_URL)%'
blog:
driver: 'pdo_mysql'
server_version: '5.7'
url: '%env(DATABASE_BLOG_URL)%'
charset: utf8mb4
orm:
auto_generate_proxy_classes: true
default_entity_manager: default
entity_managers:
default:
connection: default
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
Main:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: Main
blog:
connection: blog
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
blog:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: blog
in controller:
$entityManager = $this->getDoctrine()->getManager('blog');
$University = $entityManager->getRepository(University::class)
->findOneBy(array('Code' => $Code));
i would recommend inject the connection as a service in your Controller and leverage autowiring
//CONTROLLER
public function testController(YourService $service){
return $service->test();
}
//services.yml
App\Service\YourService:
public: true
arguments: ['#doctrine.orm.entity_manager','#doctrine.orm.blog']
//src/service/YourService.php
class YourService {
private $blog,$em;
public function __construct(EntityManager $em, EntityManager $blog) {
$this->em = $em
$this->blog = $blog;
}
public function test()
{
//connect to blog
$this->blog->getRepository(your_entity::class)->findAll();
//connect to default
$this->em->getRepository(your_entity::class)->findAll();
}
Are you trying to put the name of your second DB in the second argument of the function getRepository, like this:
$University = $entityManager->getRepository(University::class, 'blog')
->findOneBy(array('Code' => $Code));
Update 2:
Use only this configuration, without specify dir, but by using this, you will obligate to use the vanilla SQL to intercate with your DB:
blog:
connection: blog
naming_strategy: doctrine.orm.naming_strategy.underscore
my last suggestion will be to create differente folders Entities for each connection, and duplicate in it the sames entities, and like this you can use the ORM DOCTRINE properly.
I've create CompilerPass class to set some data from database as parameters:
class ParametersCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$em = $container->get('doctrine.orm.default_entity_manager');
$params = $em->getRepository(Setting::class)->findAll();
}
}
but I get this error:
An exception occurred in driver: SQLSTATE[HY000] [1102] Incorrect database name 'nv_097f203e25c61d94_resolve_database_url_c9a61b2f5dc3b858f85dcd10be22549a'
When I get the entity manager e.g. in controller via doctrine.orm.default_entity_manager service everything works fine.
doctrine.yaml:
parameters:
env(DATABASE_URL): ''
doctrine:
dbal:
driver: 'pdo_mysql'
server_version: '5.4'
charset: utf8mb4
default_table_options:
charset: utf8mb4
collate: utf8mb4_unicode_ci
url: '%env(resolve:DATABASE_URL)%'
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
You can't access a service at build time in a CompilerPass, the container is not generated yet. A CompilerPass is meant to write things in the generated .php file that will be loaded later.
You probably just want a standard service which loads your configuration in its constructor and provide them through getters.
In a Symfony 4 application I have configured multiple entity managers.
I want my functional tests to automatically create DB tables for both managers.
However, when I run my test; PHP unit encounters an error that says
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
Table 'test.example' doesn't exist
config/packages/doctrine.yaml:
doctrine:
dbal:
connections:
default:
url: '%env(resolve:DATABASE_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
custom:
url: '%env(resolve:DATABASE_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
orm:
default_entity_manager: default
auto_generate_proxy_classes: '%kernel.debug%'
entity_managers:
default:
connection: default
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
Model:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/Model'
prefix: 'App\Entity\Model'
alias: Model
custom:
connection: custom
naming_strategy: doctrine.orm.naming_strategy.underscore
mappings:
Custom:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/src/Entity/Custom'
prefix: 'App\Entity\Custom'
alias: Custom
To create tables and load Fixtures I'm currently using the Liip Functional Test Bundle.
A simple test looks like this:
tests\Functional\GeneralControllerTest.php:
class GeneralControllerTest extends WebTestCase
{
/**
* {#inheritdoc}
*/
protected function setUp()
{
$this->loadFixtures([
SomeFixtures::class,
MoreFixtures::class,
]);
}
/**
* #dataProvider providePageUris
* #test
* #param string $uri
*/
public function checkThatPageLoads($uri)
{
$client = static::createClient();
/* ... more code ... */
$client->request(Request::METHOD_GET, $uri);
static::assertEquals(Response::HTTP_OK, $client->getResponse()->getStatusCode());
}
/**
* #return array
*/
public function providePageUris()
{
return [
["/dashboard"],
];
}
}
How can I make my Test Case create database tables for the other custom Doctrine EntityManagers?
I have tried adding:
$this->loadFixtures([], true, "custom");
and also:
$this->runCommand("doctrine:schema:create --env=test --em=custom");
to the setUp() method of the Test Case, but this did not result in what is needed. The database tables all need to be created before any Fixture is loaded into the database.
To not have tables in a different entity manager and connection removed when loading data fixtures I changed the doctrine configuration with distinct environment variables.
config/packages/doctrine.yaml:
doctrine:
dbal:
connections:
default:
url: '%env(resolve:DATABASE_URL)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
custom:
url: '%env(resolve:DATABASE_URL_CUSTOM)%'
driver: 'pdo_mysql'
server_version: '5.7'
charset: utf8mb4
According to the code for the WebTestCase on GitHub the second argument should contain the name of the object manager. I am not sure if specifying custom is enough or if you have to specify the full name doctrine.entity_manager.custom though.
I'm trying to use softdelete option of gedmo/doctrine-extensions but for some reason when I call romove(), the record in database gets removed instead of updating deletedAt field.
In here, doc tells us to update config with:
$config->addFilter('soft-deleteable',
'Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter');
This is just one of the examples I tried:
# app/config/config.yml
doctrine:
orm:
entity_managers:
default:
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
References (just a few of them):
DoctrineExtensions SoftDeleteable
http://knplabs.com/en/blog/gedmo-doctrine-extensions-on-symfony2
Can't enable SoftDeleteable in Symfony2 - Unrecognized options "filters"
So the question in simple terms, how do I configure it in config.yml?
CONTROLLER
public function delete($id)
{
$profile = $this->profileRepository->findOneBy(['id' => $id]);
if (!$profile instanceof Profile) {
throw new ........
}
$this->entityManager->remove($profile);
$this->entityManager->flush();
return true;
}
ENTITY
use Gedmo\Mapping\Annotation as Gedmo;
/**
* #ORM\Entity()
* #ORM\Table(name="profile")
* #Gedmo\SoftDeleteable(fieldName="deletedAt")
*/
class Profile
{
/**
* #ORM\Column(name="deletedAt", type="datetime", nullable=true)
*/
private $deletedAt;
......
}
COMPOSER.JSON
"require": {
"symfony/symfony": "2.6.*",
"doctrine/orm": "~2.2,>=2.2.3",
"doctrine/doctrine-bundle": "~1.2",
"gedmo/doctrine-extensions": "2.3.*#dev",
......
},
CONFIG.YML
doctrine:
dbal:
default_connection: front
connections:
front:
driver: %database_driver%
host: %database_host%
........
back:
driver: %database_driver%
host: %database_host%
........
orm:
auto_generate_proxy_classes: %kernel.debug%
default_entity_manager: front
entity_managers:
front:
connection: front
mappings:
MyWebsiteBundle:
dir: Entity
FOSUserBundle: ~
back:
connection: back
MAPPING INFO:
inanzzz#inanzzz:/var/www/html/local$ php app/console doctrine:mapping:info
Found 8 mapped entities:
[OK] My\Bundle\Entity\AbstractMerchantProfile
[OK] My\Bundle\Entity\AbstractIntegration
[OK] My\Bundle\Entity\APIConsumer
[OK] My\Bundle\WebsiteBundle\Entity\User
[OK] My\Bundle\WebsiteBundle\Entity\Profile
[OK] My\Bundle\WebsiteBundle\Entity\Integration
[OK] FOS\UserBundle\Model\Group
[OK] FOS\UserBundle\Model\User
This is how I configured it
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
Solution:
Included stof/doctrine-extensions-bundle in composer.json
"stof/doctrine-extensions-bundle": "1.2.*#dev",
Package is here. Documentation is here.
Enable bundle in AppKernel:
new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle()
Since I have more than one entity managers in config.yml I did:
stof_doctrine_extensions:
orm:
em1:
softdeleteable: true
doctrine:
dbal:
default_connection: em1
connections:
em1:
driver: %database_driver%
host: %database_host%
.......
em2:
driver: %database_driver%
host: %database_host%
.......
em3:
driver: %mws_database_driver%
host: %mws_database_host%
.......
orm:
auto_generate_proxy_classes: %kernel.debug%
default_entity_manager: em1
entity_managers:
em1:
connection: em1
mappings:
MyWebsiteBundle:
dir: Entity
FOSUserBundle: ~
filters:
softdeleteable:
class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
enabled: true
em2:
connection: em2
em3:
connection: em3
Somehow I need to use aux connection / entity manager...
security.yml:
security:
providers:
administrators:
entity: { class: Hoax\PartnerBundle\Entity\Partner, property: username }
config.yml:
doctrine:
dbal:
default_connection: default
connections:
default:
driver: %database1_driver%
host: %database1_host%
port: %database1_port%
dbname: %database1_name%
user: %database1_user%
password: %database1_password%
charset: UTF8
mapping_types:
enum: string
aux:
driver: %database2_driver%
host: %database2_host%
port: %database2_port%
dbname: %database2_name%
user: %database2_user%
password: %database2_password%
charset: UTF8
mapping_types:
enum: string
orm:
auto_generate_proxy_classes: %kernel.debug%
default_entity_manager: default
entity_managers:
default:
connection: default
mappings:
HoaxNotificationsBundle: ~
HoaxPartnerBundle: ~
vpnserver:
connection: aux
mappings:
HoaxPartnerBundle: ~
vpnpayment:
connection: payment
mappings:
HoaxPartnerBundle: ~
Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php:
class EntityUserProvider implements UserProviderInterface
{
private $class;
private $repository;
private $property;
private $metadata;
public function __construct(ManagerRegistry $registry, $class, $property = null, $managerName = null)
I tried setting it like this: { class: Hoax\PartnerBundle\Entity\Partner, property: username, managerName: aux }
But having error: InvalidConfigurationException: Unrecognized options "managerName" under "security.providers.administrators.entity"
Read a little bit further: symfony.com/doc/current/cookbook/doctrine/…. If you still have trouble then update your question with the orm section of doctrine.
You also need to add the entity manager name to the provider section of the security file: symfony.com/doc/current/reference/configuration/security.html
Make sure you use manager_name and not managerName