Hello friends of symfony. I'm building a project that needs 2 connections to database. And it works nice, but if I want to get/use the second (called customer) connection by dependency injection instead of $this->container->get('doctrine.dbal.customer_connection'); it takes the default connection. I'm trying to use the dependency injection because is the new way to work with symfony and I understand that the other way will be deprecated in news versions of Symfony, so I'm updating my code to the new way to code.
I have this configuration that works nice.
config.yml
# Doctrine Configuration
doctrine:
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
customer:
driver: oci8
host: '%database_host2%'
port: '%database_port2%'
dbname: '%database_name2%'
user: '%database_user2%'
password: '%database_password2%'
charset: UTF8
So, if I use this next code inside a controller it returns what it's suppose to return, the customer connection.
$connection = $this->container->get('doctrine.dbal.customer_connection');
At the moment works good and I can get the customer connection.
So now, what I thought is create a service for this case called "QueriesCustomer", update the services.yml and finally update the parameters from the controller that I want to use with the services "QueriesCustomer" as a dependency injection ready to use in the controller.
<?php
#AppBundle/Service/QueriesOracle.php
namespace AppBundle\Service;
use Doctrine\DBAL\Connection;
class QueriesOracle
{
/**
* #var Connection
*/
private $oracleDB;
/**
* QueriesOracle constructor.
* #param Connection $oracleDB
*/
public function __construct(Connection $oracleDB)
{
$this->oracleDB = $oracleDB;
}
}
and
services.yml
services:
_defaults:
autowire: true
autoconfigure: true
public: false
AppBundle\Services\QueriesOracle:
class: AppBundle\Service\QueriesOracle
arguments:
- '#doctrine.dbal.customer_connection'
and finally the controller
<?php
namespace AppBundle\Controller;
use AppBundle\Service\QueriesOracle;
...
class AduanasController extends Controller
{
/**
* #Route("/{_locale}/xxx")
* #param Request $request
* #param QueriesOracle $queriesOracle
*/
public function nameOfFunctionAction(Request $request, QueriesOracle $queriesOracle)
{
dump($queriesOracle);die;
}
}
Can anyone tell me how to fix this "problem"? I would like to use by dependency injection both connections without problems.
Thank you in advance.
Detected the problem.... Was in service.yml AppBundle\Service"s (needs to be deleted...)"\QueriesOracle: class: AppBundle\Service\QueriesOracle
Related
I am a newbie in using Symfony2.8 and I got a validation problem.
This is how my code from dependency injection looks like --
<?php
namespace AppBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class AppExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container) {
$r = new \ReflectionClass(get_class($this));
$dir = dirname($r->getFileName());
$loader = new YamlFileLoader($container, new FileLocator($dir.'/../Resources/config'));
$loader->load('validation.yml');
}
}
And then I am trying to validate that those two columns are unique. (UniqueConstraint).
# src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\StaticContent:
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
fields: [build, name]
With StaticContent in the Entity and it complains that it can't find the StaticContent.
nebo#localhost:/var/www/html/iclei$ php app/console doctrine:schema:update --dump-sql
[Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
There is no extension able to load the configuration for "AppBundle\Entity\StaticContent" (in /var/www/html/iclei/src/AppBundle/DependencyInjection/../Resources/config/validation.yml). Looked for nam
espace "AppBundle\Entity\StaticContent", found none
What am I doing wrong ?
Also I have inside the
app/config/config.yml
framework:
#esi: ~
#translator: { fallbacks: ['%locale%'] }
secret: '%secret%'
router:
resource: '%kernel.root_dir%/config/routing.yml'
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enabled: true, enable_annotations: true }
And this is the structure of the Bundle which we are building.
DIR/src/AppBundle/Resources/config/doctrine/StaticContent.orm.yml
DIR/src/AppBundle/DependencyInjection/AppExtension.php
This is my doctrine configuration:
# Doctrine Configuration
doctrine:
dbal:
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%/data/data.db3'
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
#path: '%database_path%'
orm:
entity_managers:
default:
mappings:
AppBundle: ~
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
On I13 request I add my entity.
<?php
namespace AppBundle\Entity;
/**
* StaticContent
*/
class StaticContent
{
/**
* #var int
*/
private $id;
/**
* #var int
*/
private $build;
/**
* #var string
*/
private $name;
/**
* #var string
*/
private $type;
/**
* #var string
*/
private $data;
With their getters and setters.
AppBundle\Entity\StaticContent:
type: entity
table: null
repositoryClass: AppBundle\Repository\StaticContentRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
name:
type: string
length: 255
data:
type: blob
manyToOne:
build:
targetEntity: AppBundle\Entity\Build
inversedBy: staticContents
joinColumn:
name: build_id
referencedColumnName: id
lifecycleCallbacks: { }
Please try to enable bundle under doctrine configuration and tell is it works:
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
default:
auto_mapping: true
mappings:
YOURBundle: ~
Change AppExtension:
<?php
namespace AppBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
class AppExtension extends Extension {
/**
* {#inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container) {
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
}
}
Considering this following service class:
namespace AppBundle\Listener\Entity;
use AppBundle\Entity\Payment;
use AppBundle\Event\PaymentEvent;
use AppBundle\Event\PaymentEvents;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
final class PaymentEntityListener
{
/**
* #var EventDispatcherInterface
*/
private $eventDispatcher;
/**
* #required
*
* #param EventDispatcherInterface $eventDispatcher
*/
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
{
dump($eventDispatcher);
$this->eventDispatcher = $eventDispatcher;
}
/**
* #param Payment $payment
*/
public function postPersist(Payment $payment)
{
$this->eventDispatcher->dispatch(PaymentEvents::ADD, new PaymentEvent($payment));
}
}
The method PaymentEntityListener::setEventDispatcher should be call with the EventDispatcherInterface matched service.
This method is correctly configured according to the debug command:
$ ./bin/console debug:container --show-private AppBundle\\Listener\\Entity\\PaymentEntityListener
Information for Service "AppBundle\Listener\Entity\PaymentEntityListener"
=========================================================================
---------------- -------------------------------------------------
Option Value
---------------- -------------------------------------------------
Service ID AppBundle\Listener\Entity\PaymentEntityListener
Class AppBundle\Listener\Entity\PaymentEntityListener
Tags -
Calls setEventDispatcher
Public no
Synthetic no
Lazy no
Shared yes
Abstract no
Autowired yes
Autoconfigured yes
---------------- -------------------------------------------------
But this method is never called.
Here is my services.yml:
imports:
- { resource: legacy_aliases.yml }
services:
_defaults:
autowire: true
autoconfigure: true
public: false
_instanceof:
Doctrine\ORM\Decorator\EntityManagerDecorator:
public: true
AppBundle\:
resource: '../../src/AppBundle/*'
exclude: '../../src/AppBundle/{Entity,Repository}'
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
tags: ['controller.service_arguments']
PowerDNSBundle\:
resource: '../../src/PowerDNSBundle/*'
exclude: '../../src/PowerDNSBundle/{Entity,Repository}'
PowerDNSBundle\Doctrine\ORM\PowerDNSEntityManager:
arguments:
$wrapped: '#doctrine.orm.powerdns_entity_manager'
I don't know why the method is not called and why Symfony does not throw any exception.
FYI, the following command:
./bin/console debug:container --show-private Symfony\\Component\\EventDispatcher\\EventDispatcherInterface
Does return a service match.
Where can be the issue?
Thanks for your help.
I finally found why: This listener didn't have the correct tag:
AppBundle\Listener\Entity\:
resource: '../../src/AppBundle/Listener/Entity'
tags: ['doctrine.orm.entity_listener']
Because of that, I guess the service is not recognized by Doctrine and this one try to create the listener itself. But in this case, the method will never be called.
Error: doctrine.mongodb:generate:document No bundle Bundle was found with Symfony3.
c:\Bitnami\wampstack-5.6.20-0\apache2\htdocs\sym\patmonS1>php bin/console doctrine:mongodb:generate:document PatmonBundle:Product
PHP Warning: Module 'mongo' already loaded in Unknown on line 0
[Symfony\Component\Console\Exception\RuntimeException]
The "--filter" option does not exist.
config.tml
doctrine_mongodb:
connections:
default:
server: "%mongodb_server%"
options: {}
default_database: hello_%kernel.environment%
document_managers:
default:
mappings:
PatmonBundle: ~
#filters:
# filter-name:
# class: Class\Example\Filter\ODM\ExampleFilter
# enabled: true
metadata_cache_driver: array # array, apc, xcache, memcache
C:\Bitnami\wampstack-5.6.20-0\apache2\htdocs\sym\patmonS1\app\config\services.yml
services:
mongo_client:
class: MongoClient
# if using a username and password
arguments: ['mongodb://%mongodb_username%:%mongodb_password%#%mongodb_host%:27017']
session.handler.mongo:
class: Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler
arguments: ['#mongo_client', '%mongo.session.options%']
C:\Bitnami\wampstack-5.6.20-0\apache2\htdocs\sym\patmonS1\app\config\parameters.yml
parameters:
mongodb_server: mongodb://localhost:27017
mongodb_username: username
mongodb_password: password
mongodb_host: localhost
mongo.session.options:
db_name: mdb_patmonS1
collection: session
C:\Bitnami\wampstack-5.6.20-0\apache2\htdocs\sym\patmonS1\src\Pat\monBundle\Document\Product.php
<?php
namespace Pat\monBundle\Document;
// http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html
// http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html#cookbook-mongodb-field-types
// http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/basic-mapping.html
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
//use Doctrine\ODM\MongoDB\Mapping\Annotations\Document; with annotation #Document
/**
* #MongoDB\Document
*/
class Product
{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\Field(type="string")
*/
protected $name;
/**
* #MongoDB\Field(type="float")
*/
protected $price;
}
Just realized, that such a command does not exist in mongodb. I am new with mongodb. Nevertheless, exists command:
php bin/console doctrine:mongodb:generate:documents PatmonBundle
http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html
I am using symfony LTS with master FOS:elastica and master jms_serializer.
Config
fos_elastica:
clients:
default: { host: %elastic_host%, port: %elastic_port% }
serializer:
callback_class: FOS\ElasticaBundle\Serializer\Callback
serializer: serializer
indexes:
c_search:
client: default
types:
adverts:
mappings:
id:
type: integer
user:
type: string
Media:
type: nested
properties:
urlMedia: ~
persistence:
driver: orm
model: WebSite\MyBundle\Entity\Advert
provider: ~
listener: ~
finder: ~
Populate
php app/console fos:elastica:populate
This command work without any problem before I added the lines below. When I try to run "php app/console fos:elastica:populate" there is an infinite loop since I have added these lines:
serializer:
callback_class: FOS\ElasticaBundle\Serializer\Callback
serializer: serializer
Troubleshooting:
After this I made a simple request (without serialize because of my problem) like this on my controller :
public function testAction()
{
$repositoryManager = $this->container->get('fos_elastica.manager');
$repository = $repositoryManager->getRepository('WebSiteMyBundle:Advert');
$data = json_encode($repository->find('68200'));
return $this->render('WebSiteMyBundle:Default:test.html.twig', array(
'test'=> $data,
));
}
On my result test there is like 5 empty arrays. I know the result is good since there is normaly 5 response in my raw request but I can't find the solution to show the real content if anyone have an idea.
Ok, I was right in my comment, this issue was related to serializer and is quite logical.
Actually, if you do not specify anything, elastic will index every property and every relation in cascade which is a problem when having some circular references.
Here is what you could do to fix you problem :
First, add some properties in your group :
<?php
namespace WebSite\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
/**
* Advert
*
* #ORM\Table(name="advert")
*/
class Advert
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=55)
* #Serializer\Groups({"elastica"})
*/
private $title;
...
Then, add this in your config file :
fos_elastica:
clients:
default: { host: %elastic_host%, port: %elastic_port% }
serializer:
callback_class: FOS\ElasticaBundle\Serializer\Callback
serializer: serializer
indexes:
c_search:
client: default
types:
adverts:
serializer:
groups: [elastica]
mappings:
id:
type: integer
user:
type: string
Media:
type: nested
properties:
urlMedia: ~
persistence:
driver: orm
model: WebSite\MyBundle\Entity\Advert
provider: ~
listener: ~
finder: ~
Then, you shouldn't have any circular reference and only having title property in your elasticsearch index.
Good luck.
im not sure what ive done wrong here.
I am following the instruction on how to install the fos bundle and have come across a problem.
I am getting the following error:
PHP Fatal error: Uncaught exception
'Doctrine\ORM\Mapping\MappingException' with message 'Class
RS\Entity\User is not a valid entity or mapped super class.' in
PATH\vendor\doctrine\lib\Doctrine\ORM\Mapping\MappingException.php:142
My user class is in /src/RS/Entity/User.php
And i have'RS' => __DIR__.'/../vendor/reportsuite/src'in app/autoload.php
The class is
<?php
// /src/RS/Entity/User.php
namespace RS\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
}
As far as i can tell this is a mapped entity, unless im missing something?
Ive also tried creating the entity in by bundle and another bundle like Acme/UserBundle/Entity/User.php
# Doctrine Configuration
doctrine:
dbal:
default_connection: default
connections:
default:
dbname: axpdb
user: %database_user%
password: %database_password%
host: %database_host%
port: %database_port%
charset: UTF8
reportsuite:
dbname: reportsuite
user: %database_user%
password: %database_password%
host: %database_host%
port: %database_port%
charset: UTF8
orm:
entity_managers:
default:
connection: default
mappings:
ReportSuiteMainMenuBundle: ~
reportsuite:
connection: reportsuite
mappings:
# Security
jms_security_extra:
secure_controllers: true
secure_all_services: false
# FOS User Config
#fos_user:
# db_driver: orm
# firewall_name: main
# user_class: RS\Entity\User
# model_manager_name: reportsuite
I have 2 databases that I need to access and I have commented out the fos stuff so i can continue working.
Did You checkd a namespace ?
I think it should be:
namespace Namespace\YourBundle\Entity
You can use entites from all of Your bundles.
Run
touch Entity/*
and you are OK.
Had this problem - don't forget the annotation * #ORM\Entity like below:
/**
* Powma\ServiceBundle\Entity\User
*
* #ORM\Entity
* #ORM\Table(name="users")
*/