Custom config with service/di references - php

For my project I want to specify some custom configuration. I have a bunch of 'mappers' that have some properties and will refer to other services.
For example, I would like my config to look like this:
self_service:
mappers:
branche_vertalingen:
data_collector: "#self_service.branche_vertalingen.data_collector"
data_loader: "#self_service.branche_vertalingen.data_loader"
map_data: SelfServiceBundle\Entity\BrancheVertalingMapData
Where self_service is the bundle name, mappers is the 'container' where all the mappers are defined. And branche_vertalingen is one of the defined mappers, there can (and will) be many more. At the moment, each mapper has a data_collector and a data_loader that refer to services defined in the bundle's services.yml, and a map_data property which refers to an entity's class name.
I have put this configuration in SelfServiceBundle/Resources/config/config.yml and import it in app/config/config.yml.
I have create a SelfServiceExtension class according to this article. In the extension's load() method I receive my defined configuration as an array. So far, so good.
The problem I am having is that the value for data_collector I receive is just the defined string, and not the service I was expecting. No problem, I thought. I have a $container available, I will just look it up, but I can't get the service there.
The question: How do I make sure I can get the service I reference in the config?
I had already tried doing the same in a parameters block so that I wouldn't even need a bundle Extension, but doing that I got this error: You cannot dump a container with parameters that contain references to other services. So after that I tried to do it via an Extension.

As I wrote in the comments, I think tagged services are a good fit for this. It allows you to very easily add or remove mappers just by tagging a service. This way there's no hard requirement for all mappers to live at the same place or similar.
Using interfaces to ensure that everything is wired correctly also allows for easy extension.
To see how this can even incorporate your initial idea, see the example at the end of this answer.
usage
/** #var $mapperManager MapperManager */
$mapperManager = $this->get('app.mapper_manager');
dump($mapperManager);
foreach ($mapperManager->getMappers('branche_vertalingen') as $mapper) {
dump($mapper);
}
implementation
(closely following the official docs):
service.yml
services:
app.mapper_manager:
class: AppBundle\Mapper\Manager
# mappers
app.mapper_1:
public: false
class: AppBundle\Mapper\DefaultMapper
arguments:
- "a"
- "b"
- SelfServiceBundle\Entity\BrancheVertalingMapData
tags:
- { name: app.mapper, branch: branche_vertalingen }
app.mapper_2:
public: false
class: AppBundle\Mapper\DefaultMapper
arguments:
- "c"
- "d"
- SelfServiceBundle\Entity\BrancheVertalingMapData
tags:
- { name: app.mapper, branch: branche_vertalingen }
app.mapper_3:
public: false
class: AppBundle\Mapper\DefaultMapper
arguments:
- "e"
- "f"
- SelfServiceBundle\Entity\BrancheVertalingMapData
tags:
- { name: app.mapper, branch: other_branch }
the compiler pass:
<?php
// src/AppBundle/DependencyInjection/Compiler/MapperCompilerPass.php
namespace AppBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
class MapperCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->has('app.mapper_manager')) {
return;
}
$definition = $container->findDefinition('app.mapper_manager');
$taggedServices = $container->findTaggedServiceIds('app.mapper');
foreach ($taggedServices as $id => $tags) {
foreach ($tags as $attributes) {
$definition->addMethodCall('addMapper', [$attributes['branch'], new Reference($id)]);
}
}
}
}
using the compiler pass:
<?php
// src/AppBundle/AppBundle.php
namespace AppBundle;
use AppBundle\DependencyInjection\Compiler\MapperCompilerPass;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class AppBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new MapperCompilerPass());
}
}
a simple manager class (call it whatever fits better):
<?php
// src/AppBundle/Mapper/Manager.php
namespace AppBundle\Mapper;
class Manager
{
private $mappers = [];
public function addMapper($branch, MapperInterface $mapper)
{
if (!array_key_exists($branch, $this->mappers)) {
$this->mappers[$branch] = [];
}
$this->mappers[$branch][] = $mapper;
}
public function getMappers($branch)
{
if (!array_key_exists($branch, $this->mappers)) {
// handle invalid access
// throw new \InvalidArgumentException('%message%');
}
return $this->mappers[$branch];
}
}
a default mapper class (this is actually not required, but could make things easier to start with):
<?php
// src/AppBundle/Mapper/DefaultMapper.php
namespace AppBundle\Mapper;
class DefaultMapper implements MapperInterface
{
private $dataCollector;
private $dataLoader;
private $mapData;
public function __construct($dataCollector, $dataLoader, $mapData)
{
$this->dataCollector = $dataCollector;
$this->dataLoader = $dataLoader;
$this->mapData = $mapData;
}
public function getDataCollector()
{
return $this->dataCollector;
}
public function getDataLoader()
{
return $this->dataLoader;
}
public function getMapData()
{
return $this->mapData;
}
}
and finaly a simple interface to use with the data mappers:
<?php
// src/AppBundle/Mapper/MapperInterface.php
namespace AppBundle\Mapper;
interface MapperInterface
{
public function getDataCollector();
public function getDataLoader();
public function getMapData();
}
a little extra
With an additional compiler pass (or only, see code-comments) you could also extend the above solution:
using an extra compiler pass, like:
<?php
// src/AppBundle/DependencyInjection/Compiler/MapperCollectionCompilerPass.php
namespace AppBundle\DependencyInjection\Compiler;
use AppBundle\Mapper\DefaultMapper;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Definition;
class MapperCollectionCompilerPass implements CompilerPassInterface
{
private $parameterName;
public function __construct($parameterName)
{
$this->parameterName = $parameterName;
}
public function process(ContainerBuilder $container)
{
if (!$container->has('app.mapper_manager')) {
return;
}
if (!$container->hasParameter($this->parameterName)) {
return;
}
$definition = $container->findDefinition('app.mapper_manager');
$mappers = $container->getParameter($this->parameterName);
foreach ($mappers as $branch => $meta) {
$mapper = new Definition(DefaultMapper::class, [
new Reference($meta['data_collector']),
new Reference($meta['data_loader']),
$meta['map_data'],
]);
$mapper
->setPublic(false)
->addTag('app.mapper', ['branch' => $branch])
;
$container->addDefinitions([$mapper]);
// If you don't want to use tags, simply add the 'addMethodCall'
// from MapperCompilerPass here
// $definition->addMethodCall('addMapper', [$branch, $mapper]);
}
}
}
adding it to the bundle:
<?php
// src/AppBundle/AppBundle.php
namespace AppBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use AppBundle\DependencyInjection\Compiler\MapperCompilerPass;
use AppBundle\DependencyInjection\Compiler\MapperCollectionCompilerPass;
class AppBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new MapperCollectionCompilerPass('mappers'));
$container->addCompilerPass(new MapperCompilerPass());
}
}
and adding the config:
# app/config/services.yml
parameters:
mappers:
branche_vertalingen:
# !note the missing #
data_collector: app.some_service
data_loader: app.some_service
map_data: SelfServiceBundle\Entity\BrancheVertalingMapData

Related

Symfony6 changing the controller manually using the "kernel.controller" event. How to inject the service container?

The application that I am building is not going to work in a traditional way. All the routes ar going to be stored in the database. And based on the route provided I need to get the correct controller and action to be executed.
As I understand this can be achieved using the "kernel.controller" event listener: https://symfony.com/doc/current/reference/events.html#kernel-controller
I am trying to use the docs provided, but the example here does not exacly show how to set up a new callable controller to be passed. And I have a problem here, because I dont know how to inject the service container to my newly called controller.
At first the setup:
services.yaml
parameters:
db_i18n.entity: App\Entity\Translation
developer: '%env(DEVELOPER)%'
category_directory: '%kernel.project_dir%/public/uploads/category'
temp_directory: '%kernel.project_dir%/public/uploads/temp'
product_directory: '%kernel.project_dir%/public/uploads/product'
app.supported_locales: 'lt|en|ru'
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
App\Translation\DbLoader:
tags:
- { name: translation.loader, alias: db }
App\Extension\TwigExtension:
arguments:
- '#service_container'
tags:
- { name: twig.extension }
App\EventListener\RequestListener:
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onControllerRequest }
The listener:
RequestListener.php
<?php
namespace App\EventListener;
use App\Controller\Shop\HomepageController;
use App\Entity\SeoUrl;
use Doctrine\Persistence\ManagerRegistry;
use Exception;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Security;
class RequestListener
{
public ManagerRegistry $doctrine;
public RequestStack $requestStack;
public function __construct(ManagerRegistry $doctrine, RequestStack $requestStack)
{
$this->doctrine = $doctrine;
$this->requestStack = $requestStack;
}
/**
* #throws Exception
*/
public function onControllerRequest(ControllerEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
if(str_contains($this->requestStack->getMainRequest()->getPathInfo(), '/admin')) {
return;
}
$em = $this->doctrine->getManager();
$pathInfo = $this->requestStack->getMainRequest()->getPathInfo();
;
$route = $em->getRepository(SeoUrl::class)->findOneBy(['keyword' => $pathInfo]);
if($route instanceof SeoUrl) {
switch ($route->getController()) {
case 'homepage':
$controller = new HomepageController();
$event->setController([$controller, $route->getAction()]);
break;
default:
break;
}
} else {
throw new Exception('Route not found');
}
}
}
So this is the most basic example. I get the route from the database, if it a "homepage" route, I create the new HomepageController and set the action. However I am missing the container interface that I dont know how to inject. I get this error:
Call to a member function has() on null
on line: vendor\symfony\framework-bundle\Controller\AbstractController.php:216
which is:
/**
* Returns a rendered view.
*/
protected function renderView(string $view, array $parameters = []): string
{
if (!$this->container->has('twig')) { // here
throw new \LogicException('You cannot use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
}
return $this->container->get('twig')->render($view, $parameters);
}
The controller is as basic as it gets:
HomepageController.php
<?php
namespace App\Controller\Shop;
use App\Repository\CategoryRepository;
use App\Repository\Shop\ProductRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class HomepageController extends AbstractController
{
#[Route('/', name: 'index', methods: ['GET'])]
public function index(): Response
{
return $this->render('shop/index.html.twig', [
]);
}
}
So basically the container is not set. If I dump the $event->getController() I get this:
RequestListener.php on line 58:
array:2 [▼
0 => App\Controller\Shop\HomepageController {#417 ▼
#container: null
}
1 => "index"
]
I need to set the container by doing $controller->setContainer(), but what do I pass?
Do not inject the container, controllers are services too and manually instanciating them is preventing you from using constructor dependency injection. Use a service locator which contains only the controllers:
Declared in config/services.yaml:
# config/services.yaml
services:
App\EventListener\RequestListener:
arguments:
$serviceLocator: !tagged_locator { tag: 'controller.service_arguments' }
Then in the event listener, add the service locator argument and fetch the fully configured controllers from it:
# ...
use App\Controller\Shop\HomepageController;
use Symfony\Component\DependencyInjection\ServiceLocator;
class RequestListener
{
# ...
private ServiceLocator $serviceLocator;
public function __construct(
# ...
ServiceLocator $serviceLocator
) {
# ...
$this->serviceLocator = $serviceLocator;
}
public function onControllerRequest(ControllerEvent $event)
{
# ...
if($route instanceof SeoUrl) {
switch ($route->getController()) {
case 'homepage':
$controller = $this->serviceLocator->get(HomepageController::class);
# ...
break;
default:
break;
}
}
# ...
}
}
If you dump any controller you will see that the container is set. Same will go for additionnal service that you autowire from the constructor.

In Symfony, how to call controller function in Menubuilder?

I have written one function as getAccess() in controller file Appbundle/Controller/BackendController.php.
I want to access this controller's method in Menu/Menubuilder.php file. How can I do that?
Menu and Appbundle folders are at same level.
For me, a controller can not be called in menuBuilder and it would not be "clean". I suggest you create a manager or service that contains this feature and call your service in your controller and in MenuBuilder.
namespace App\Service;
class MessageGenerator
{
public function getHappyMessage()
{
$messages = [
'You did it! You updated the system! Amazing!',
'That was one of the coolest updates I\'ve seen all day!',
'Great work! Keep going!',
];
$index = array_rand($messages);
return $messages[$index];
}
}
What version of symfony are you on?
You can use Trait
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
So, you can create your function getAccess() in trait file and just use it in BackendController.php and Menubuilder.php
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
I have created service as follows:
namespace AppBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class UserAccessService {
private $conn;
private $container;
private $tokenStorage;
public function __construct(EntityManagerInterface $entityManager, ContainerInterface $container, TokenStorageInterface $tokenStorage) {
$this->conn = $entityManager;
$this->container = $container;
$this->tokenStorage = $tokenStorage;
}
and added following code in services.yml:
app.service.useraccessservice:
class: AppBundle\Services\UserAccessService
arguments: ['#doctrine.orm.default_entity_manager','#service_container','#security.token_storage']
app.menu_builder:
class: AppBundle\Menu\MenuBuilder
arguments: ["#knp_menu.factory", "#security.authorization_checker", '#security.token_storage', '#translator', '#app.service.useraccessservice','#kernel']
public: true
tags:
- { name: knp_menu.menu_builder, method: createMainMenu, alias: main_menu }
- { name: knp_menu.menu_builder, method: createManagementMenu, alias: management_menu }
- { name: knp_menu.menu_builder, method: createUserMenu, alias: user_menu }
It works as expected.

Get service via class name from iterable - injected tagged services

I am struggling to get a specific service via class name from group of injected tagged services.
Here is an example:
I tag all the services that implement DriverInterface as app.driver and bind it to the $drivers variable.
In some other service I need to get all those drivers that are tagged app.driver and instantiate and use only few of them. But what drivers will be needed is dynamic.
services.yml
_defaults:
autowire: true
autoconfigure: true
public: false
bind:
$drivers: [!tagged app.driver]
_instanceof:
DriverInterface:
tags: ['app.driver']
Some other service:
/**
* #var iterable
*/
private $drivers;
/**
* #param iterable $drivers
*/
public function __construct(iterable $drivers)
{
$this->drivers = $drivers;
}
public function getDriverByClassName(string $className): DriverInterface
{
????????
}
So services that implements DriverInterface are injected to $this->drivers param as iterable result. I can only foreach through them, but then all services will be instantiated.
Is there some other way to inject those services to get a specific service via class name from them without instantiating others?
I know there is a possibility to make those drivers public and use container instead, but I would like to avoid injecting container into services if it's possible to do it some other way.
You no longer (since Symfony 4) need to create a compiler pass to configure a service locator.
It's possible to do everything through configuration and let Symfony perform the "magic".
You can make do with the following additions to your configuration:
services:
_instanceof:
DriverInterface:
tags: ['app.driver']
lazy: true
DriverConsumer:
arguments:
- !tagged_locator
tag: 'app.driver'
The service that needs to access these instead of receiving an iterable, receives the ServiceLocatorInterface:
class DriverConsumer
{
private $drivers;
public function __construct(ServiceLocatorInterface $locator)
{
$this->locator = $locator;
}
public function foo() {
$driver = $this->locator->get(Driver::class);
// where Driver is a concrete implementation of DriverInterface
}
}
And that's it. You do not need anything else, it just workstm.
Complete example
A full example with all the classes involved.
We have:
FooInterface:
interface FooInterface
{
public function whoAmI(): string;
}
AbstractFoo
To ease implementation, an abstract class which we'll extend in our concrete services:
abstract class AbstractFoo implements FooInterface
{
public function whoAmI(): string {
return get_class($this);
}
}
Services implementations
A couple of services that implement FooInterface
class FooOneService extends AbstractFoo { }
class FooTwoService extends AbstractFoo { }
Services' consumer
And another service that requires a service locator to use these two we just defined:
class Bar
{
/**
* #var \Symfony\Component\DependencyInjection\ServiceLocator
*/
private $service_locator;
public function __construct(ServiceLocator $service_locator) {
$this->service_locator = $service_locator;
}
public function handle(): string {
/** #var \App\Test\FooInterface $service */
$service = $this->service_locator->get(FooOneService::class);
return $service->whoAmI();
}
}
Configuration
The only configuration needed would be this:
services:
_instanceof:
App\Test\FooInterface:
tags: ['test_foo_tag']
lazy: true
App\Test\Bar:
arguments:
- !tagged_locator
tag: 'test_foo_tag'
Alternative to FQCN for service names
If instead of using the class name you want to define your own service names, you can use a static method to define the service name. The configuration would change to:
App\Test\Bar:
arguments:
- !tagged_locator
tag: 'test_foo_tag'
default_index_method: 'fooIndex'
where fooIndex is a public static method defined on each of the services that returns a string. Caution: if you use this method, you won't be able to get the services by their class names.
A ServiceLocator will allow accessing a service by name without instantiating the rest of them. It does take a compiler pass but it's not too hard to setup.
use Symfony\Component\DependencyInjection\ServiceLocator;
class DriverLocator extends ServiceLocator
{
// Leave empty
}
# Some Service
public function __construct(DriverLocator $driverLocator)
{
$this->driverLocator = $driverLocator;
}
public function getDriverByClassName(string $className): DriverInterface
{
return $this->driverLocator->get($fullyQualifiedClassName);
}
Now comes the magic:
# src/Kernel.php
# Make your kernel a compiler pass
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class Kernel extends BaseKernel implements CompilerPassInterface {
...
# Dynamically add all drivers to the locator using a compiler pass
public function process(ContainerBuilder $container)
{
$driverIds = [];
foreach ($container->findTaggedServiceIds('app.driver') as $id => $tags) {
$driverIds[$id] = new Reference($id);
}
$driverLocator = $container->getDefinition(DriverLocator::class);
$driverLocator->setArguments([$driverIds]);
}
And presto. It should work assuming you fix any syntax errors or typos I may have introduced.
And for extra credit, you can auto register your driver classes and get rid of that instanceof entry in your services file.
# Kernel.php
protected function build(ContainerBuilder $container)
{
$container->registerForAutoconfiguration(DriverInterface::class)
->addTag('app.driver');
}

How to get Doctrine to work inside a helper function on Symfony2

I need to get doctrine working inside my helper, im trying to use like i normaly do in a controller:
$giftRepository = $this->getDoctrine( )->getRepository( 'DonePunctisBundle:Gift' );
But this gave me:
FATAL ERROR: CALL TO UNDEFINED METHOD
DONE\PUNCTISBUNDLE\HELPER\UTILITYHELPER::GETDOCTRINE() IN
/VAR/WWW/VHOSTS/PUNCTIS.COM/HTTPDOCS/SRC/DONE/PUNCTISBUNDLE/HELPER/UTILITYHELPER.PH
What Im missing here?
EDIT:
services file
services:
templating.helper.utility:
class: Done\PunctisBundle\Helper\UtilityHelper
arguments: [#service_container]
tags:
- { name: templating.helper, alias: utility }
Firts lines of helper file
<?php
namespace Done\PunctisBundle\Helper;
use Symfony\Component\Templating\Helper\Helper;
use Symfony\Component\Templating\EngineInterface;
class UtilityHelper extends Helper {
/*
* Dependency injection
*/
private $container;
public function __construct( $container )
{
$this->container = $container;
}
The problem here is that your Helper class is not container-aware; that is, it has no idea about all the services Symfony has loaded (monolog, twig, ...and doctrine).
You fix this by passing "doctrine" to it. This is called Dependency Injection, and is one of the core things that makes Symfony awesome. Here's how it works:
First, give your Helper class a place for the Doctrine service to live, and require it in the Helper's constructor:
class UtilityHelper
{
private $doctrine;
public function __construct($doctrine)
{
$this->doctrine = $doctrine;
}
public function doSomething()
{
// Do something here
}
}
Then, you use services.yml to define how Symfony should construct that instance of Helper:
services:
helper:
class: Done\PunctisBundle\Helper\UtilityHelper
arguments: [#doctrine]
In this case, #doctrine is a placeholder that means "insert the Doctrine service here".
So now, in your Controller, or in anything else that is container-aware, you can get access to Doctrine through the Helper class like this:
class SomeController()
{
public function someAction()
{
$this->get("helper")->doctrine->getRepository(...);
}
}
EDIT
After looking at your edit, it appears that you're injecting the entire service container into the Helper class. That's not a best practice -- you should only inject what you need. However, you can still do it:
services.yml
services:
helper:
class: Done\PunctisBundle\Helper\UtilityHelper
arguments: [#service_container]
UtilityHelper.php
class UtilityHelper
{
private $container;
public function __construct($container)
{
$this->container = $container;
}
public function doSomething()
{
// This won't work, because UtilityHelper doesn't have a getDoctrine() method:
// $this->getDoctrine()->getRepository(...)
// Instead, think about what you have access to...
$container = $this->container;
// Now, you need to get Doctrine
// This won't work... getDoctrine() is a shortcut method, available only in a Controller
// $container->getDoctrine()->getRepository(...)
$container->get("doctrine")->getRepository(...)
}
}
I've included a few comments there that highlight some common pitfalls. Hope this helps.
In Helper, Services etc you cannot use it like in actions.
You need to pass it like argument to youre Helper via service description in conf file(services.yml or *.xml).
Example:
services:
%service_name%:
class: %path_to_youre_helper_class%
arguments: [#doctrine.orm.entity_manager]
tags:
- { name: %name% }
And dont forget catch it in __construct of youre Helper.
Example:
use Doctrine\ORM\EntityManager;
....
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
You can use it like:
public function myMethod()
{
$repo = $this->em->getRepository('DonePunctisBundle:Gift');
}

How to inject a repository into a service in Symfony?

I need to inject two objects into ImageService. One of them is an instance of Repository/ImageRepository, which I get like this:
$image_repository = $container->get('doctrine.odm.mongodb')
->getRepository('MycompanyMainBundle:Image');
So how do I declare that in my services.yml? Here is the service:
namespace Mycompany\MainBundle\Service\Image;
use Doctrine\ODM\MongoDB\DocumentRepository;
class ImageManager {
private $manipulator;
private $repository;
public function __construct(ImageManipulatorInterface $manipulator, DocumentRepository $repository) {
$this->manipulator = $manipulator;
$this->repository = $repository;
}
public function findAll() {
return $this->repository->findAll();
}
public function createThumbnail(ImageInterface $image) {
return $this->manipulator->resize($image->source(), 300, 200);
}
}
Here is a cleaned up solution for those coming from Google like me:
Update: here is the Symfony 2.6 (and up) solution:
services:
myrepository:
class: Doctrine\ORM\EntityRepository
factory: ["#doctrine.orm.entity_manager", getRepository]
arguments:
- MyBundle\Entity\MyClass
myservice:
class: MyBundle\Service\MyService
arguments:
- "#myrepository"
Deprecated solution (Symfony 2.5 and less):
services:
myrepository:
class: Doctrine\ORM\EntityRepository
factory_service: doctrine.orm.entity_manager
factory_method: getRepository
arguments:
- MyBundle\Entity\MyClass
myservice:
class: MyBundle\Service\MyService
arguments:
- "#myrepository"
I found this link and this worked for me:
parameters:
image_repository.class: Mycompany\MainBundle\Repository\ImageRepository
image_repository.factory_argument: 'MycompanyMainBundle:Image'
image_manager.class: Mycompany\MainBundle\Service\Image\ImageManager
image_manipulator.class: Mycompany\MainBundle\Service\Image\ImageManipulator
services:
image_manager:
class: %image_manager.class%
arguments:
- #image_manipulator
- #image_repository
image_repository:
class: %image_repository.class%
factory_service: doctrine.odm.mongodb
factory_method: getRepository
arguments:
- %image_repository.factory_argument%
image_manipulator:
class: %image_manipulator.class%
In case if do not want to define each repository as a service, starting from version 2.4 you can do following, (default is a name of the entity manager):
#=service('doctrine.orm.default_entity_manager').getRepository('MycompanyMainBundle:Image')
Symfony 3.3, 4 and 5 makes this much simpler.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your code, all you need to do is use composition over inheritance - one of SOLID patterns.
1. Create own repository without direct dependency on Doctrine
<?php
namespace MycompanyMainBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
use MycompanyMainBundle\Entity\Image;
class ImageRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(Image::class);
}
// add desired methods here
public function findAll()
{
return $this->repository->findAll();
}
}
2. Add config registration with PSR-4 based autoregistration
# app/config/services.yml
services:
_defaults:
autowire: true
MycompanyMainBundle\:
resource: ../../src/MycompanyMainBundle
3. Now you can add any dependency anywhere via constructor injection
use MycompanyMainBundle\Repository\ImageRepository;
class ImageService
{
public function __construct(ImageRepository $imageRepository)
{
$this->imageRepository = $imageRepository;
}
}
In my case bases upon #Tomáš Votruba answer and this question I propose the following approaches:
Adapter Approach
Without Inheritance
Create a generic Adapter Class:
namespace AppBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
class RepositoryServiceAdapter
{
private $repository=null;
/**
* #param EntityManagerInterface the Doctrine entity Manager
* #param String $entityName The name of the entity that we will retrieve the repository
*/
public function __construct(EntityManagerInterface $entityManager,$entityName)
{
$this->repository=$entityManager->getRepository($entityName)
}
public function __call($name,$arguments)
{
if(empty($arrguments)){ //No arguments has been passed
$this->repository->$name();
} else {
//#todo: figure out how to pass the parameters
$this->repository->$name(...$argument);
}
}
}
Then foreach entity Define a service, for examplein my case to define a (I use php to define symfony services):
$container->register('ellakcy.db.contact_email',AppBundle\Services\Adapters\RepositoryServiceAdapter::class)
->serArguments([new Reference('doctrine'),AppBundle\Entity\ContactEmail::class]);
With Inheritance
Same step 1 mentioned above
Extend the RepositoryServiceAdapter class for example:
namespace AppBundle\Service\Adapters;
use Doctrine\ORM\EntityManagerInterface;
use AppBundle\Entity\ContactEmail;
class ContactEmailRepositoryServiceAdapter extends RepositoryServiceAdapter
{
public function __construct(EntityManagerInterface $entityManager)
{
parent::__construct($entityManager,ContactEmail::class);
}
}
Register service:
$container->register('ellakcy.db.contact_email',AppBundle\Services\Adapters\RepositoryServiceAdapter::class)
->serArguments([new Reference('doctrine')]);
Either the case you have a good testable way to function tests your database beavior also it aids you on mocking in case you want to unit test your service without the need to worry too much on how to do that. For example, let us suppose we have the following service:
//Namespace definitions etc etc
class MyDummyService
{
public function __construct(RepositoryServiceAdapter $adapter)
{
//Do stuff
}
}
And the RepositoryServiceAdapter adapts the following repository:
//Namespace definitions etc etc
class SomeRepository extends \Doctrine\ORM\EntityRepository
{
public function search($params)
{
//Search Logic
}
}
Testing
So you can easily mock/hardcode/emulate the behavior of the method search defined in SomeRepository by mocking aither the RepositoryServiceAdapter in non-inheritance approach or the ContactEmailRepositoryServiceAdapter in the inheritance one.
The Factory Approach
Alternatively you can define the following factory:
namespace AppBundle\ServiceFactories;
use Doctrine\ORM\EntityManagerInterface;
class RepositoryFactory
{
/**
* #param EntityManagerInterface $entityManager The doctrine entity Manager
* #param String $entityName The name of the entity
* #return Class
*/
public static function repositoryAsAService(EntityManagerInterface $entityManager,$entityName)
{
return $entityManager->getRepository($entityName);
}
}
And then Switch to php service annotation by doing the following:
Place this into a file ./app/config/services.php (for symfony v3.4, . is assumed your ptoject's root)
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
$definition = new Definition();
$definition->setAutowired(true)->setAutoconfigured(true)->setPublic(false);
// $this is a reference to the current loader
$this->registerClasses($definition, 'AppBundle\\', '../../src/AppBundle/*', '../../src/AppBundle/{Entity,Repository,Tests,Interfaces,Services/Adapters/RepositoryServiceAdapter.php}');
$definition->addTag('controller.service_arguments');
$this->registerClasses($definition, 'AppBundle\\Controller\\', '../../src/AppBundle/Controller/*');
And cange the ./app/config/config.yml (. is assumed your ptoject's root)
imports:
- { resource: parameters.yml }
- { resource: security.yml }
#Replace services.yml to services.php
- { resource: services.php }
#Other Configuration
Then you can clace the service as follows (used from my example where I used a Dummy entity named Item):
$container->register(ItemRepository::class,ItemRepository::class)
->setFactory([new Reference(RepositoryFactory::class),'repositoryAsAService'])
->setArguments(['$entityManager'=>new Reference('doctrine.orm.entity_manager'),'$entityName'=>Item::class]);
Also as a generic tip, switching to php service annotation allows you to do trouble-free more advanced service configuration thin one above. For code snippets use a special repository I made using the factory method.
For Symfony 5 it is really simple, without need of services.yml to inject the dependency:
inject the Entity Manager in the service constructor
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
Then get the repository :
$this->em->getRepository(ClassName::class)
by replacing ClassName with your entity name.

Categories