How to prevent Symfony 4 service override? - symfony

I have base /config/services.yaml which stores many services in my Symfony 4.3 project. For example:
My\Namespace\Service:
- '#My\Namespace\Dependency'
For my test purposes, I have config/test/test_services.yaml where I store services with 'test.' prefix to test private services, making them public in test env.
One of the services, declared in test_services.yaml has no prefix. It is identical by its name (FQCN) to another one defined in services.yaml. They have different constructor arguments of the same type.
Test one (/config/test_services.yaml) has mocked dependencies returning fixtures data:
My\Namespace\Service:
- '#My\Namespace\MockedDependency'
Is there a way to prevent service override to not replace mocked service with real one during test execution in test env?

Solution for this situation is create services_test.yaml file and place it under /config folder along with services.yaml.
In that case, symfony will not override service and will use one defined in services_test.yaml during tests execution

Related

Is there a way to create an IDbContext interface for DI (using AutoFac)?

Is there a way to create an IDbContext interface for DI (using AutoFac)?
i am using asp.net mvc 5 & EF 6.
and i would like to create an Interface for Dependency Injection.
There is some way to do it?
Currently i am register my Context class and it will work fine
builder.RegisterType<CustomContext>().SingleInstance().InstancePerLifeTimeScope();
DbContext's should be short-lived. A common pattern for working with EF Contexts is the Unit of Work pattern. There are a few out there for EF that can help manage the scope of a DbContext. At worst for ASP.Net you would want the DbContext lifetime set to the Request, no longer.
Option 1: (Recommended) Register a unit of work implementation (Such as Medhime's DbContextScope) and let that manage the DbContext scope. These follow the Interface/Concrete definitions to work well with DI.
Option 2: Register a DbContextFactory and use that to provide DbContexts. I.e.
using (var context = ContextFactory.Create())
{
// ....
}
Where ContextFactory is a defined DbContextFactory class implementing an IDbContextFactory interface.
Option 3: Register the DbContext itself as a PerRequest lifetime scope.
If your goal is to inject DbContexts to facilitate testing, I would highly recommend adopting a Repository pattern (Not a Generic Repository pattern I.e. Repository<TEntity>) and utilizing either Option 1 or Option 2. The advantage of a repository is that it serves as a boundary for the unit tests. Your "code under test" can then be served a Mocked repository class which in turn returns stubbed entities or IEnumerable<TEntity>/IQueryable<TEntity>. Mocking DbContexts and their DbSets is honestly a PITA. Repository methods can be tested if & as desired using integration-style tests talking to a real database.

Replace a private service in the Symfony container for testing

Is it possible to replace a private service in the DI container? I need to do this in my test environment, so that I can run integration tests but still mock HTTP calls to external APIs.
For example, I have this code that sets the mock for the HttpClientInterface:
$response = new MockResponse('"some json body"');
$client = new MockHttpClient([$response]);
self::$container->set(HttpClientInterface::class, $client);
// Execute controller / command and perform assertions
// ...
I have already tried to define the HttpClientInterface as a public service for my test environment with the config below, but this does not work as it isn't instantiable (it's an interface).
services:
Symfony\Contracts\HttpClient\HttpClientInterface:
public: true
I resolved this issue myself for my specific case by creating my own MockHttpClient class that doesn't require setting the responses in the constructor. Replacing a service in the container at runtime seemed to be the wrong way to go based on how Symfony have intended for the container to be immutable

Symfony 3.3 service mocks for functional tests

Before Symfony 3.3 it was allowed to set a mocked service onto the container. Now with 3.3 a deprecation warning is thrown because the service is already pre-defined.
What is the new standard way to overwrite an existing or pre-defined service in the container to set a mocked service for a functional test?
E.g. in our case we set a new entity manager with a new mocked connection pointing to a cloned database for testing.
$container->set('doctrine.orm.entity_manager', $testEm);
Setting the "doctrine.orm.entity_manager" pre-defined service is deprecated since Symfony 3.3 and won't be supported anymore in Symfony 4.0.
I had the very same problem just a few days ago and I wrote a library to trick Symfony's DIC: https://github.com/TiMESPLiNTER/proxy-mock
The idea is to override the service in the config_test.yml with a "proxy" from the original service class which redirects all the calls to a mock which then can be set dynamically in the test case.
# config_test.yml
services:
timesplinter.proxy_mock.factory:
class: timesplinter\ProxyMock\ProxyMockFactory
acme.api.client:
factory: 'timesplinter.proxy_mock.factory:create'
arguments: ['Acme\AppBunde\Services\ApiClient']
This will override the service defined in the original service.(xml|yml) with a proxy of it.
In the test case you can then do something like this:
// Your container aware test case (this exmaple is for PHPUnit)
$mock = $this->getMockBuilder(ApiClient::class)->disableOriginalConstructor()->getMock();
$container->set('acme.api.client')->setMock($mock);
With this your test will run against the mock you provide using the setMock() method.
The library is very new so some feature may be missing. If you use it and miss something please provide a pull request with the desired feature.

How to access the configuration parameters from the model layer in Symfony 2?

Is there a way to access the configuration parameters in config.yml from the model layer? From the controller I can use $this->container->getParameter('xyz'). But how can it be done from a class in the Model layer?
In symfony2 Entities are designed as POPOs, meaning that they shouldn't really have access to anything outside of their scope.
If you need some config option in one of your entities, consider passing it as a parameter from the controller like so:
$entityName->methodName($param1, $this->container->getParameter('xyz'));
This could (will) break DIC pattern, but you could use a singleton class to "globalize" what you need.
To feed your globals, use bootmethod from Bundle class (where you can access DIC stuff hence configuration).
Or more simple, add a static field to your Entity.
Quick & dirty solution, don't abuse it ;-)
You can use Dependency Injection and add your model to your services.yml file, and like every other service you make you can provide other services as constructor parameters. The only downside is you call $derp = $this->get("your_service_name"); instead of $derp = new Derp();.
For example:
# src/Derp/LolBundle/Resources/config/services.yml
services:
derp:
class: \Derp\LolBundle\Entity\Message
arguments: [#service_container]
#service_container is a service found using php app/console container:debug. It will function identically to $this->container in your controllers and it is provided to the constructor of your class. See here for more information on how to use service containers.
As previously mentioned they are POPOs (Plain Old PHP Objects) and the previous method of dependency injection is poor choice simply because you will have to remember to provide your model entity with the same object every time you use it (which is a hassle) and Symfony2 services are a way to mitigate that pain.

How can I access a service outside of a controller with Symfony2?

I'm building a site that relies quite heavily on a third party API so I thought it would make sense to package up the API wrapper as a service, however I'm starting to find instances where it would be useful to have access to it outside of a controller such as in an entity repository.
Also related to that is it would be useful to be able to get access to config values outside of a controller (again such as in an entity repository).
Can anyone tell me if this is possible and if not is there a suggested approach to doing this kind of thing?
thanks for any help
The Symfony distribution relies heavily on dependency injection. This means that usually, dependencies are injected directly into your object via the constructor, the setters or via other means (like reflection over properties). Your API wrapper service is then a dependency for other objects of your application.
That being said, it would be rather difficult to inject this service in an entity repository's constructor because it already requires some other parameters and I think it would not be possible to inject them because of the way we request the repository for an entity.
What you could do is to create another service which will be responsible of doing the work you were about to do in the entity repository. This way, you will be able to inject the entity manager, which will be used to retrieve the entity repository, you custom service and also another service holding your configuration values (There are other ways to share configuration values).
In my use case, I use a Facebook helper service that wraps Facebook API calls. This service is then injected where I need it. My entity repository is only responsible of doing database calls so it receives only the arguments it needs and not the whole dependency. Thus, it will not receive the helper but rather only the arguments needed to do a request, for example, a Facebook user id. In my opinion, this is the way to do it since I think the entity repository should not have dependencies on such helper objects.
Here a small example using YAML as the configuration:
# app/config/config.yml
services:
yourapp.configuration_container:
class: Application/AcmeBundle/Common/ConfigurationContainer
# You could inject configurations here
yourapp.api_wrapper:
class: Application/AcmeBundle/Service/ApiWrapperService
# Inject other arguments if needed and update constructor in consequence
yourapp.data_access:
class: Application/AcmeBundle/Data/Access/DatabaseAccessService
arguments:
entityManager: "#doctrine.orm.entity_manager"
apiWrapperService: "#yourapp.api_wrapper"
configuration: "#yourapp.configuration_container"
# Application/AcmeBundle/Common/ConfigurationContainer.php
public ConfigurationContainer
{
public function __construct()
{
// Initialize your configuration values or inject them in the constructor
}
}
# Application/AcmeBundle/Service/ApiWrapperService.php
public ApiWrapperService
{
public function __construct()
{
// Do some stuff
}
}
# Application/AcmeBundle/Data/Access/DatabaseAccessService.php
public DatabaseAccessService
{
public function __construct(EntityManager $entityManager, ApiWrapperService $apiWrapperService, ConfigurationContainer $configuration)
{
...
}
}
The at sign (#) in the config.yml file means that Symfony should inject another service ,having the id defined after the at sign, and not a simple string. For the configuration values, as I said previously, there is other means to achieve the same goal like using parameters or a bundle extension. With a bundle extension, you could define the configuration values directly into the config.yml and your bundle would read them.
In conclusion, this should give you the general idea of injecting services. Here a small list of documentation on the subject. Alot of links use the XML service definition instead of the YAML definition but you should be able to understand them quite easily.
Symfony Official DI
Fabien Potencier's articles on DI
Richard Miller's articles on DI (Check in his blog for the other DI articles)
Take note that the configuration I'm giving is working for Beta1 of Symfony2. I didn't update yet to Beta2 so there could be some stuff not working as they are in the Beta2 version.
I hope this will help you defining a final solution to your problem. Don't hesitate to ask other questions if you want clarifications or anything else.
Regards,
Matt
I would wrap this kind of behavior in a Symfony service(like a manager).
i would not inject any parameters or logic into the entity repositories, as they should mainly be used to fetch data using object manager queries.
I would put the logic in the services and if the service , require a database access it will call the entity repository to fetch data.

Resources