I'm looking for a way to have doctrine (in a symfony 5 application) connect with the database details stored in an external XML file (instead of .env).
However I can't seem to be finding a solution.
Reading the XML file isn't the problem, I just can't find how to pass the parameters on the doctrine.
I've tried to use a doctrine.php file but fails to connect.
I've also tried to use a wrapper class and called the parent construct method but it seems it isn't recommended.
Has anybody every managed to achieve something of the sort ?
Thanks !
Symfony lets you add configuration written in php. See https://symfony.com/doc/current/configuration.html#configuration-formats
That allows to do the following:
Import an additional configuration file in services.yaml
imports:
- { resource: 'my-db-config.php' }
my-db-config.php:
<?php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
function readConfig() {
$myConfig = '' // read from your xml file
return $myConfig
}
return static function (ContainerConfigurator $container) {
$container
->parameters()
->set('my.param', readConfig());
};
in use your new param in doctrine.yaml
doctrine:
dbal:
connections:
default:
url: '%my.param%'
Related
this is my first post, so i will try to be clear
So i need to define some constants in the Symfony configuration (in a .yaml file, i guess)
I know i could define them throw public const MY_CONST but that is not what I want.
I guess this is what i need (the second part, i am not using Abstract controller as i am not in a controller)
https://symfony.com/doc/current/configuration.html#accessing-configuration-parameters
But I just can't get it to work. Could anyone help me, by giving me an exemple, or maybe an other way to do ?
Thanks guys.
The parameters you described can be used in the configuration defined as eg;
parameters:
the_answer: 42
You can then use these values in further configuration things (see below for example). Or if you want to handle these values in a controller you can (not recommended anymore) use $this->getParameter('the_answer') to get the value.
Binding arguments (recommended):
This approach wil bind values which you can then get (auto-magically injected) in a controller function/service by referencing the argument.
The values can range from simple scalar values to services, .env variables, php constants and all of the other things the configuration can parse.
# config/services.yaml
services:
_defaults:
bind:
string $helloWorld: 'Hello world!' # simple string
int $theAnswer: '%the_answer%' # reference an already defined parameter.
string $apiKey: '%env(REMOTE_API)%' # env variable.
Then these get injected in a service/controller function when we do something like:
public function hello(string $apiKey, int $theAnswer, string $helloWorld) {
// do things with $apiKey, $theAnswer and $helloWorld
}
More details and examples can be found in the symfony docs https://symfony.com/doc/current/service_container.html#binding-arguments-by-name-or-type
Inject into service (alternative)
You can also directly inject it into the defined service using arguments.
# config/services.yaml
services:
# explicitly configure the service
App\Updates\SiteUpdateManager:
arguments:
$adminEmail: 'manager#example.com'
How i can create and use own global config with keys/values in symfony?
I was try set keys/values in parameters.yml under parameters line which been in this file after instalation and get it like $pageTitle = $this->getParameter('myKey'); and it works but i want own whole config file with structure for ex. $this->getParameter('myParameters.myKey') so:
I was created new file:
#app/config/myConfig.yml
myParameters:
myKey: myValue
In config.yml i added:
#app/config/config.yml
imports:
- { resource: myConfig.yml }
and in controller:
$pageTitle = $this->getParameter('myKey');
And i have exception:
FileLoaderLoadException in FileLoader.php line 118: There is no extension able to load the configuration for "inyconfig" (in....
EDIT
This example works but you must do one little change - myParameters change to parameters and everything is work like a charm.
You have to do a dependency injection e.g. BundleNameDependencieInjection related of your bundle and then create Configuration class that provide configure external dependence and/or external configurations
Have a look there http://symfony.com/doc/current/bundles/configuration.html#processing-the-configs-array
In parameters you can create some scalar or array variables that can be called in some circumstances in your case you may create an array with some range like that :
parameters:
# scalar
one.two.three: something
# array
oneBis:
twoBis:
threeBis: somethingBis
Use parameters instead of myParameters.
So, put in app/config/myConfig.yml:
parameters:
myKey: myValue
I have a Yaml loader that loads additional config items for a "profile" (where one application can use different profiles, e.g. for different local editions of the same site).
My loader is very simple:
# YamlProfileLoader.php
use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Yaml\Yaml;
class YamlProfileLoader extends FileLoader
{
public function load($resource, $type = null)
{
$configValues = Yaml::parse($resource);
return $configValues;
}
public function supports($resource, $type = null)
{
return is_string($resource) && 'yml' === pathinfo(
$resource,
PATHINFO_EXTENSION
);
}
}
The loader is used more or less like this (simplified a bit, because there is caching too):
$loaderResolver = new LoaderResolver(array(new YamlProfileLoader($locator)));
$delegatingLoader = new DelegatingLoader($loaderResolver);
foreach ($yamlProfileFiles as $yamlProfileFile) {
$profileName = basename($yamlProfileFile, '.yml');
$profiles[$profileName] = $delegatingLoader->load($yamlProfileFile);
}
So is the Yaml file it's parsing:
# profiles/germany.yml
locale: de_DE
hostname: %profiles.germany.host_name%
At the moment, the resulting array contains literally '%profiles.germany.host_name%' for the 'hostname' array key.
So, how can I parse the % parameters to get the actual parameter values?
I've been trawling through the Symfony 2 code and docs (and this SO question and can't find where this is done within the framework itself. I could probably write my own parameter parser - get the parameters from the kernel, search for the %foo% strings and look-up/replace... but if there's a component ready to be used, I prefer to use this.
To give a bit more background, why I can't just include it into the main config.yml: I want to be able to load app/config/profiles/*.yml, where * is the profile name, and I am using my own Loader to accomplish this. If there's a way to wildcard import config files, then that might also work for me.
Note: currently using 2.4 but just about ready to upgrade to 2.5 if that helps.
I've been trawling through the Symfony 2 code and docs (and this SO question and can't find where this is done within the framework itself.
Symfony's dependency injection component uses a compiler pass to resolve parameter references during the optimisation phase.
The Compiler gets the registered compiler passes from its PassConfig instance. This class configures a few compiler passes by default, which includes the ResolveParameterPlaceHoldersPass.
During container compilation, the ResolveParameterPlaceHoldersPass uses the Container's ParameterBag to resolve strings containing %parameters%. The compiler pass then sets that resolved value back into the container.
So, how can I parse the % parameters to get the actual parameter values?
You'd need access to the container in your ProfileLoader (or wherever you see fit). Using the container, you can recursively iterate over your parsed yaml config and pass values to the container's parameter bag to be resolved via the resolveValue() method.
Seems to me like perhaps a cleaner approach would be for you to implement this in your bundle configuration. That way your config will be validated against a defined structure, which can catch configuration errors early. See the docs on bundle configuration for more information (that link is for v2.7, but hopefully will apply to your version also).
I realise this is an old question, but I have spent quite a while figuring this out for my own projects, so I'm posting the answer here for future reference.
I tried a lot of options to resolve %parameter% to parameters.yml but no luck at all. All I can think of is parsing %parameter% and fetch it from container, no innovation yet.
On the other hand I don't have enough information about your environment to see the big picture but I just come up with another idea. It can be quite handy if you declare your profiles in your parameters.yml file and load it as an array in your controller or service via container.
app/config/parameters.yml
parameters:
profiles:
germany:
locale: de_DE
host_name: http://de.example.com
uk:
locale: en_EN
host_name: http://uk.example.com
turkey:
locale: tr_TR
host_name: http://tr.example.com
You can have all your profiles as an array in your controller.
<?php
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
$profiles = $this->container->getParameter('profiles');
var_dump($profiles);
return $this->render('AcmeDemoBundle:Default:index.html.twig');
}
}
With this approach
you don't have to code a custom YamlLoader
you don't have to worry about importing parameters into other yml files
you can have your profiles as an array anytime you have the $container in your hand
you don't have to load/cache profile files one by one
you don't have to find a wildcard file loading solution
If I got your question correctly, this approach can help you.
I completed a project in Symfony2 and am now improving/refactoring it. One small task is to put some parameters/credentials in an external config file.
I know that I can import that file by using:
# app/config/config.yml
imports:
- { resource: parameters.php }
or:
// app/config/config.php
$loader->import('parameters.php');
But I want to know the difference/benefits of using yml, xml or php as an external file. Is one of them ' safer' or 'better' then the other perhaps?
In practice there's no difference, this is rather question what you are used to.
In my opinion parameters.yml is just key-value stuff so yml is just perfect for this.
Yml is probably most clear but maybe not most fluent.
Check this question for more general differences between various formats.
I am building a custom plugin, which consists of schema which I am trying to keep tightly coupled with the plugin. For example, I have a plugins/userPlugin/config/doctrine/schema.yml which references a 'store-rw-user' connection. My goal is to force the project's databases.yml to contain a connection for 'store-rw-user', this way the project will be responsible for setting up the separate user connection.
However, when I attempt to access plugin related code I keep getting: Doctrine_Manager_Exception Unknown connection: store-rw-user.
Here is the related snippet of the plugin schema file:
# plugins/userPlugin/config/doctrine/schema.yml
connection: store-rw-user
User:
tableName: user
actAs: [Timestampable]
And here is the related snippet of the BaseUser.class.php (generated when doing a model build):
<?php
// lib/model/doctrine/userPlugin/base/BaseUser.class.php
// Connection Component Binding
Doctrine_Manager::getInstance()->bindComponent('User', 'store-rw-user');
....
And finally the related snippet of the project's databases.yml file:
# config/databases.yml
all:
store-rw-user:
class: sfDoctrineDatabase
param:
....
On the outset, everything looks configured correctly. The plugin schema.yml resulted in the base class binding the correct database connection, which exists in the project's databases.yml file. However, I am running into the aforementioned issue. I'd like to know if there is another approach to this issue before I start trying to manipulate doctrine connection manager manually via the plugins initialize() method.
-- Update --
After further investigation, it appears that sfDatabaseManager is aware of the 'store-rw-user' connection, however, Doctrine_Manager is not. At first I thought this was maybe due to the order in which I added plugins within the main project config file, but it only affected whether sfDatabaseManager was connection aware, but for the sake of completeness, here is the snippet of the project config file:
// config/ProjectConfiguration.class.php
class ProjectConfiguration extends sfProjectConfiguration
{
....
public function setup()
{
....
$this->enablePlugins(
array(
'sfDoctrinePlugin',
'userPlugin'
)
);
}
}
And just in case it matters, here is the app.yml for the userPlugin:
# plugins/userPlugin/config/app.yml
# This entry was needed so build-model was executed, the plugin schema file would be pulled in for build as well
all:
userPlugin:
config_dir: %SF_PLUGINS_DIR%/userPlugin/config
recursive: true
And here is the confusing snippet of code, where I have access to 'store-rw-user' connection via sfDatabaseManager but not Doctrine_Manager, which is a problem because the error is being thrown from Doctrine_Manager and not sfDatabaseManager:
// plugins/userPlugin/config/userPluginConfiguration.class.php
class userPluginConfiguration extends sfPluginConfiguration
{
public function initialize()
{
parent::initialize();
var_dump(Doctrine_Manager::getInstance()->getConnections());
$config = ProjectConfiguration::getActive();
$manager = new sfDatabaseManager($config);
var_dump($manager->getDatabase('store-rw-user'));
exit;
}
}
And the results:
array (size=0)
empty
object(sfDoctrineDatabase)[53]
protected '_doctrineConnection' =>
object(Doctrine_Connection_Mysql)[55]
protected 'driverName' => string 'Mysql' (length=5)
protected 'dbh' => null
protected 'tables' =>
array (size=0)
empty
protected '_name' => string 'store-rw-user' (length=13)
....
Not sure what's going on, tried looking at other plugins to see how they deal, and they don't have any database references that I could find.
After adding some debug code to select source files (Doctrine_Manager), I finally saw that in the above code snippet in the initialize() method, that by simply configuring sfDatabaseManager, doctrine then became aware of the connection. In short, my method ended up looking like this:
class userPluginConfiguration extends sfPluginConfiguration
{
public function initialize()
{
parent::initialize();
// Don't ask me why, without this the needed db connection never gets initialized and plugin craps out
$manager = new sfDatabaseManager(ProjectConfiguration::getActive());
}
}
And, magically, doctrine was now aware of all the connections in the project's databases.yml file. Seems weak to me that I have to explicitly make this call, but at least I can get on with some coding.