Symfony 2: get (default_locale) parameter from config.yml - symfony

Ok, I wan't to to something extremely simple, I just want to get this value from app/config/config.yml
framework:
default_locale: nl
I want to get this value in an EventListener.. Can anyone help?
Edit 1: (is this right)? but i dont use the DependencyInjection classes here.. im confused..
services:
core_locale.locale_listener:
class: Eyee\CoreBundle\EventListener\LocaleListenerDefault
arguments: ["%kernel.default_locale%"]
<?php
namespace Eyee\CoreBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* use this class if no database Languages available..
*/
class LocaleListenerDefault implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($default_locale = 'en')
{
$this->defaultLocale = $default_locale;
}`enter code here`

I doesn't get what is your problem. To use an eventlistener you need to register the service in a service file. There you can pass argument to the constructor as you wrote above:
services:
core_locale.locale_listener:
class: Eyee\CoreBundle\EventListener\LocaleListenerDefault
arguments: ["%kernel.default_locale%"]
This should work.
Or what is your problem, what's not working there?

it depends wether you have access to the container in your class.
In a controller you can do:
$locale = $this->container->getParameter('framework.default_locale');
There are numerous answers on stackoverflow that already answer this question.
For a non-controller class you need to use dependency injection.
Please read the documentation chapters Introduction to Parameters.

Related

How to use Symfony autowiring with multiple entity managers

I would like to use the autowiring in a service that use 2 different entity manager. How to achieve something like that ?
use Doctrine\ORM\EntityManager;
class TestService
{
public function __construct(EntityManager $emA, EntityManager $emB)
{
}
}
My service.yml file use to be configured like that :
app.testservice:
class: App\Services\TestService
arguments:
- "#doctrine.orm.default_entity_manager"
- "#doctrine.orm.secondary_entity_manager"
There are already two good answers posted but I'd like to add a third as well as some context to help chose which approach to use in a given situation.
emix's answer is very simple but a bit fragile in that it relies on the name of the argument for injecting the correct service. Which is fine but you won't get any help from your IDE and sometimes might be a bit awkward. The answer should probably use EntityManagerInterface but that is a minor point.
DynlanKas's answer requires a bit of code in each service to locate the desired manager. It's okay but can be a bit repetitive. On the other hand, the answer is perfect when you don't know in advance exactly which manager is needed. It allows you to select a manager based on some dynamic information.
This third answer is largely based on Ron's Answer but refined just a bit.
Make a new class for each entity manager:
namespace App\EntityManager;
use Doctrine\ORM\Decorator\EntityManagerDecorator;
class AEntityManager extends EntityManagerDecorator {}
class BEntityManager extends EntityManagerDecorator {}
Don't be alarmed that you are extending a decorator class. The class has the same interface and the same functionality as a 'real' entity manager. You just need to inject the desired manager:
# config/services.yaml
App\EntityManager\AEntityManager:
decorates: doctrine.orm.a_entity_manager
App\EntityManager\BEntityManager:
decorates: doctrine.orm.b_entity_manager
This approach requires making a new class for each entity manager as well as a couple of lines of configuration, but allows you to simply typehint against the desired class:
public function __construct(AEntityManager $emA, BEntityManager $emB)
{
}
It is, arguably, the most robust and standard way to approach the original question.
Dylan's answer violates the Demeter's Law principle. It's very easy and elegant since Symfony 3.4, meet Local service binding:
services:
_defaults:
bind:
$emA: "#doctrine.orm.default_entity_manager"
$emB: "#doctrine.orm.secondary_entity_manager"
Then in your service the autoloading will do the hard work for you:
class TestService
{
public function __construct(EntityManager $emA, EntityManager $emB)
{
…
}
}
The easy way would be to autowire ManagerRegistry in your constructor and use it to get the managers you want by using the names of the entity manger you have set in your configuration file (doctrine.yaml) :
use Doctrine\Common\Persistence\ManagerRegistry;
class TestService
{
private $emA;
private $emB;
public function __construct(ManagerRegistry $doctrine)
{
$this->emA = $doctrine->getManager('emA');
$this->emB = $doctrine->getManager('emB');
}
}
And you should be able to use them as you want.
Another way would be to follow this answer by Ron Mikluscak
Simply use EntityManagerInterface $secondaryEntityManager
If you're using Symfony's framework bundle (which I'm pretty sure you are), then Symfony >= 4.4 automatically generates camelcased autowiring aliases for every Entitymanger you define.
You can simply get a list of them using the debug:autowiring console command. For your configuration above, this should look something like this:
bin/console debug:autowiring EntityManagerInterface
Autowirable Types
=================
The following classes & interfaces can be used as type-hints when autowiring:
(only showing classes/interfaces matching EntityManagerInterface)
EntityManager interface
Doctrine\ORM\EntityManagerInterface (doctrine.orm.default_entity_manager)
Doctrine\ORM\EntityManagerInterface $defaultEntityManager (doctrine.orm.default_entity_manager)
Doctrine\ORM\EntityManagerInterface $secondaryEntityManager (doctrine.orm.secondary_entity_manager)
As described in https://symfony.com/doc/4.4/doctrine/multiple_entity_managers.html:
Entity managers also benefit from autowiring aliases when the framework bundle is used. For example, to inject the customer entity manager, type-hint your method with EntityManagerInterface $customerEntityManager.
So you should only need:
use Doctrine\ORM\EntityManagerInterface;
class TestService
{
public function __construct(
EntityManagerInterface $defaultEntityManager,
EntityManagerInterface $secondaryEntityManager
) {
// ...
}
}
The name $defaultEntityManager isn't mandatory, though it helps to distinguish between the two. Every argument that's typehinted with an EntityManagerInterface and isn't in the list returned by debug:autowiring EntityManagerInterface will result in the default Entitymanager being autowired.
Note: As written in the documentation and shown in the output of debug:autowiring, you need to use EntityManagerInterface for this aliased autowiring, not the actual EntityManager class. In fact, you should always autowire the Entitymanager using EntityManagerInterface.

get container parameter in my custom classes Symfony2

I have the class, it declare as service. When I get() my service I run some method and this method require two params what I want to let user configure in config.yml. How I can get these parameters in this class? Maybe exist some way to do this in my service definition? Or I need extend my class from ContainerAware (if I am right its bad practice)? Thanks!
You can inject parameters into your service using %param_name% syntax
services.yml
services:
your_service:
class: Acme\DemoBundle\YourClass
arguments: [#some.other.service, %my_parameter%]
parameters.yml
parameters:
my_parameter: my_value
You can use call them using the constructor
acme.your_service:
class: Acme\DemoBundle\YourService
arguments: [%param1%]
in the class
class YourService {
protected $param1;
public function __construct($param1) {
$this->param1 = $param1;
}
}

Doctrine PHPCR-ODM under Symfony not detecting mapped Document class

I am attempting to integrate PHPCR-ODM with an existing Symfony project, and am having trouble getting it to (presumably) detect my mapped Document class. Specifically, I get an error like this when attempting to persist a Document of my class MyDocument:
[Doctrine\Common\Persistence\Mapping\MappingException]
The class 'Example\Common\ORM\Document\MyDocument' was not found in the chain configured namespaces Doctrine\ODM\PHPCR\Document
My class is in a potentially strange namespace because this project uses Doctrine ORM as well, and thus far I've just added a new space for mapped Documents off of that, but I can't imagine the choice of namespace name affects the functionality.
Per the docs, I have added to my app/autoload.php:
AnnotationRegistry::registerFile(__DIR__.'/../vendor/doctrine/phpcr-odm/lib/Doctrine/ODM/PHPCR/Mapping/Annotations/DoctrineAnnotations.php');
My app/config/config.yml includes the following (with parameters set in parameters.yml):
doctrine_phpcr:
session:
backend:
type: jackrabbit
url: %jackrabbit_url%
workspace: %jackrabbit_workspace%
username: %jackrabbit_user%
password: %jackrabbit_password%
odm:
auto_mapping: true
My document class lives in src/Example/Common/ORM/Document/MyDocument.php and looks like:
<?php
namespace Example\Common\ORM\Document;
use Doctrine\ODM\PHPCR\Mapping\Annotations as PHPCRODM;
/**
* #PHPCRODM\Document
*/
class MyDocument
{
/**
* #PHPCRODM\Id
*/
private $id;
/**
* #PHPCRODM\ParentDocument
*/
private $parent;
/**
* #PHPCRODM\Nodename
*/
private $name;
// .. etc
Finally, the code I am using to test the integration is inside a simple console command, and looks like:
use Example\Common\ORM\Document\MyDocument;
// ...
$documentManager = $this->container->get('doctrine_phpcr.odm.default_document_manager');
$document = new MyDocument();
$document->setParent($documentManager->find(null, '/'));
$document->setName('ExampleName');
$documentManager->persist($document);
$documentManager->flush();
I have verified that my MyDocument class is being correctly loaded, but it seems that the annotations are not being processed in a way that is making the DocumentManager aware that it is a mapped Document class.
My guess is that I have overlooked some simple configuration step, but from looking repeatedly and thoroughly at the docs for PHPCR, PHPCR-ODM, and even Symfony CMF, I can't seem to find anything. Most of the examples out there involve using PHPCR via Symfony CMF, and I wasn't able to find many (any?) real world examples of PHPCR-ODM being integrated in a regular Symfony project.
edit: The Eventual Solution
I followed the advice that #WouterJ gave below and it fixed my problem, and I further followed his suggestion of adding a compiler pass to my Symfony bundle to make this work with a non-standard namespace (i.e., something other than YourBundle\Document). In my case, this is going into a library that will be re-used elsewhere rather than a bundle, so it was appropriate.
To do this, I added a method to the src/Example/Bundle/ExampleBundle/ExampleBundle.php file like so:
<?php
namespace Example\Bundle\ExampleBundle;
use Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ExampleBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$mappedDirectories = array(
realpath(__DIR__ . '/../../Common/ODM/Document')
);
$mappedNamespaces = array(
'Example\Common\ODM\Document'
);
$phpcrCompilerClass = 'Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass';
if (class_exists($phpcrCompilerClass)) {
$container->addCompilerPass(
DoctrinePhpcrMappingsPass::createAnnotationMappingDriver(
$mappedNamespaces,
$mappedDirectories
));
}
}
}
That code allows any mapped document classes to be placed in the Example\Common\ODM\Document namespace and it will pick them up. This example uses annotations but the same pattern can be used for XML or YAML mappings (see the Doctrine\Bundle\PHPCRBundle\DependencyInjection\Compiler\DoctrinePhpcrMappingsPass class for method signatures).
I found that I also needed to define the doctrine_phpcr.odm.metadata.annotation_reader service for this to work, which I did in app/config.yml:
services:
doctrine_phpcr.odm.metadata.annotation_reader:
class: Doctrine\Common\Annotations\AnnotationReader
There may be a better way to do that, but that was enough to make it work for me.
The document should be placed in the Document namespace of the bundle, not the ORM\Document namespace.
If you really want to put it in the ORM\Document namespace (which is very strange, because we are talking about an ODM not an ORM), you can use the doctrine mapping compiler pass: http://symfony.com/doc/current/cookbook/doctrine/mapping_model_classes.html

symfony2 custom repository extending EntityRepository

I am trying to implement a custom repository class in symfony2, and I want it to extend EntityRepository class. I am having trouble with passing the getting arguments to the parent (i.e. EntityRepository) constructor. This is the signiture of parent constructor:
public function __construct($em, Mapping\ClassMetadata $class)
So I had to add this to my services.yml file, in order to get the arguments:
parameters:
user_provider.class: Untitled\F5Bundle\Security\UserRepository
services:
user_meta_data:
class: Doctrine\ORM\Mapping\ClassMetaData
arguments:
name: "Untitled\F5Bundle\Entity\User"
user_provider:
class: "%user_provider.class%"
arguments:
entityManager: "#doctrine.orm.entity_manager"
meta_data: "#user_meta_data"
And I also added the annotation tag to my User class (which I'm not sure if it was neccessary)
Now when I run it, it raises an error. the message says:
FatalErrorException: Error: Class 'Doctrine\ORM\Mapping\ClassMetaData' not found
in /mnt/data/Projects/F5/app/cache/dev/appDevDebugProjectContainer.php line 2749
(/mnt/data/Projects/F5/ is where I keep the code)
I don't get it. What's wrong here? What am I doing wrong?
Metadata is obtained with the MetadataFactory. As an example you can see how it works in EntityManager.
public function getClassMetadata($className)
{
return $this->metadataFactory->getMetadataFor($className);
}
You can retrieve you repository as service as well. Look at this question.
You don't need to inject these constructor arguments yourself, just specify which repository class you want to use:
/**
* #Entity(repositoryClass="MyProject\UserRepository")
*/
class User
{
...
}
See also http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#entity
You miss typed classname "ClassMetaData" should be ClassMetadata
class: Doctrine\ORM\Mapping\ClassMetadata

generateUrl outside controller

Is there a possibility to use generateUrl() method outside of controllers?
I tried to use it in a custom repository class with $this->get('router'), but it didn't work.
update
I've found a temporary solution here:
http://www.phamviet.net/2012/12/09/symfony-2-inject-service-as-dependency-in-to-repository/
I injected the whole service container into my repository, although it's "not recommended".
But it works for now.
update2
Injecting router instead of the whole container is probably a better idea :)
If you take a look in the source code of Controller::generateUrl(), you see how it's done:
$this->container->get('router')->generate($route, $parameters, $referenceType);
Basically you just enter the name of the route ($route here); if exists, some parameters ($parameters) and the type of reference (one of the constants of the UrlGeneratorInterface)
Don't inject the container into your repository... Really, don't !
If I were you, I would create a service and injects the router in it. In this service, I would create a method, that uses the repository and adds the needed code using the router.
That's way less dirty and easy to use/understand for another developer.
Inject the router itself into your EntityRepsitory (like described on Development Life blog's post Symfony 2: Injecting service as dependency into doctrine repository), then you can use $this->router->generate('acme_route');
in symfony 4 and Sylius when the FormType extends an (ex.) AbstractResourceType
class PostType extends AbstractResourceType
{
private $router;
public function __construct(RouterInterface $router, $dataClass, $validationGroups = [])
{
$this->router = $router;
parent::__construct($dataClass, $validationGroups);
}
}
Services.yaml :
app.post.form.type:
class: App\Form\Admin\Post\PostType
tags:
- { name: form.type }
arguments: ['#router.default', '%app.model.post.class%' ]

Resources