Symfony 4 autowire not working with root namespaces - php

On standard there is everything put under App namespace.
So if I will have such structure with TestController having public function xxx(TestInterface $test); everything works as should.
-src
-Core
-TestInterface (App\Core)
-Api
-Controller
-TestController (App\Api\Controller)
-Domain
-Service
-TestService implements TestInterface (App\Domain\Service)
Now the problem is my project does not have App prefix.
My structure looks like this:
-src
-Core
-TestInterface (Core)
-Api
-Controller
-TestController (Api\Controller)
-Domain
-Service
-TestService implements TestInterface (Domain\Service)
composer.json
"autoload": {
"psr-4": {
"": "src/"
}
},
services.yaml
Core\:
resource: '../src/Core/*'
exclude: '../src/Core/{Entity,Migrations,Tests,Kernel.php}'
Domain\:
resource: '../src/Domain/*'
exclude: '../src/Domain/{Entity,Migrations,Tests,Kernel.php}'
Api\Controller\:
resource: '../src/Api/Controller'
tags: ['controller.service_arguments']
The most funny part of this is that almost everything works good, including dependency injection as long as I use direct class namespaces. Only finding by interface doesn't work.
This works:
public function xxx(TestService $test)
This doesn't work:
public function xxx(TestInterface $test)
Here is the error:
Cannot resolve argument $test of
"Api\Controller\TestController::xxx()":
Cannot autowire service ".service_locator.EcpiaYx": it references interface "Core\TestInterface" but no such service exists.
You should maybe alias this interface to the existing "Domain\TestService" service.

Related

Symfony 6 - Class declared in services.yaml not found

I have a problem with registering a class as a service in services.yaml.
I have created a class MenuBuilder.php in Symfony 6 that looks somewhat like this.
src/Menu/MenuBuilder.php
namespace App\Menu;
class MenuBuilder
{
public function createMainMenu(array $options)
{
// method logic
}
}
Now, when I want to register it as a service: (and use it in twig with KnpMenuBundle)
config/services.yaml
parameters:
services:
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
app.menu_builder:
class: App\Menu\MenuBuilder
arguments: [ "#knp_menu.factory" ]
tags:
- { name: knp_menu.menu_builder, method: createMainMenu, alias: main }
I get an error Class "App\Menu\MenuBuilder" not found.
I tried making some other classes (ex. Test/TestClass) and namespaces and it doesn't work with freshly created classes.
On the other hand it i fiddled around with the naming and it recognized my entities and factories.
I tried clearing the cache
I am in development mode
I am getting this message when calling {{ knp_menu_render('main') }} in twig.
My composer autoload:
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
symfony console debug:container app.menubuilder gives me this:
Information for Service "app.menu_builder"
==========================================
---------------- -------------------------------------------------------------
Option Value
---------------- -------------------------------------------------------------
Service ID app.menu_builder
Class App\Menu\MenuBuilder
Tags knp_menu.menu_builder (method: createMainMenu, alias: main)
Public no
Synthetic no
Lazy no
Shared yes
Abstract no
Autowired yes
Autoconfigured yes
Usages knp_menu.menu_provider.lazy
---------------- -------------------------------------------------------------
! [NOTE] The "app.menu_builder" service or alias has been removed or inlined when the container was compiled.
How do i get Symfony to recognize my classses?

controller has no container set error after chaning directory structure

I start new project and install fresh copy of Symfony 5 (microservice skeleton), and add first controller HealthCheckController to the default folder src/Controller, at this moment all is fine, I can get access to it from browser.
In next step I change a project name in composer.json and all related namespaces in code to
"autoload": {
"psr-4": {
"Project\\SubProject\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Project\\SubProject\\Tests\\": "tests/"
}
},
and in service.yaml
Project\SubProject\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
- '../src/Tests/'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
Project\SubProject\Controller: # assuming you have namespace like that
resource: '../src/Controller/'
tags: [ 'controller.service_arguments' ]
everything still works.
Next step is to change directory structure, add layers and modules. So I move Kernel.php to the Common/Infrastructure/Symfony/ (ofcourse I change path to config files in the kernel) and controller to folder Common/Interfaces/Controller and change configs in the service.yaml
Project\SubProject\:
resource: '../src/'
exclude:
- '../src/Common/Infrastructure/Symfony/DependencyInjection/'
- '../src/Common/Infrastructure/Symfony/Kernel.php'
- '../src/Module1/Infrastructure/Entity/'
- '../src/Module2/Infrastructure/Entity/'
- '../src/Module3/Infrastructure/Entity/'
- '../src/Module1/Test/'
- '../src/Module2/Test/'
- '../src/Module3/Test/'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
Project\SubProject\Common\Interfaces\Controller\: # assuming you have namespace like that
resource: '../src/Common/Interfaces/Controller/'
tags: [ 'controller.service_arguments' ]
and in routes/annotation/yaml
controllers:
resource: ../../src/Common/Interfaces/Controller
type: annotation
kernel:
resource: ../../src/Common/Infrastructure/Symfony/Kernel.php
type: annotation
and now I'm getting error Project\SubProject\Common\Interfaces\Controller\HealthCheckController" has no container set, did you forget to define it as a service subscriber?
What I'm doing wrong, I forgot to change something???
I know you can tell me you need to add container to controller like this
Project\SubProject\Common\Interfaces\Controller\HealthCheckController:
calls:
- method: setContainer
arguments: ['#service_container']
but it's stupid to configure each controller manually when autowire feature turned on, and when it worked with a default directory structure.
Also I clear cache by CLI command and manually deleting folder.
It was somewhat difficult to follow exactly what your configuration files ended as. I don't have a specific answer for you but I was a bit intrigued at the notion of moving Kernel.php. You did not mention moving the config directory so I chose to leave it where it was and:
namespace Project\SubProject\Common\Infrastructure\Symfony;
class Kernel extends BaseKernel
{
protected function configureContainer(ContainerConfigurator $container): void
{
$base = $this->getProjectDir();
$container->import($base . '/config/{packages}/*.yaml');
$container->import($base . '/config/{packages}/'.$this->environment.'/*.yaml');
$container->import($base . '/config/services.yaml');
$container->import($base . '/config/{services}_'.$this->environment.'.yaml');
}
# same for configureRoutes
# project/config/services.yaml
services:
_defaults:
autowire: true
autoconfigure: true
Project\SubProject\:
resource: '../src/'
exclude:
- '../src/Common/Infrastructure/Symfony/Kernel.php'
Project\SubProject\Common\Interfaces\Controller\:
resource: '../src/Common/Interfaces/Controller/'
tags: ['controller.service_arguments']
# project/config/routes/annotations.yaml
controllers:
resource: ../../src/Common/Interfaces/Controller/
type: annotation
Tweaked index.php and console to use the new Kernel path and it all worked as expected.
I should point out that as long as you are extending from AbstractController then you don't actually need the Controller section in services.yaml at all. It's quite puzzling why you seem to be getting a controller service but setContainer is not being called.
bin/console debug:container HealthCheckController
Class Project\SubProject\Common\Interfaces\Controller\HealthCheckController
Tags controller.service_arguments
container.service_subscriber
Calls setContainer
The Calls setContainer is obviously the important line.
I'm guessing you do have a typo somewhere and I suspect you did not actually start your namespace with Project\SubProject. But again it does work as expected.
Just for my own reference I checked in my test project.

Could not find any fixture services to load

i know this question has been asked already multiple times:
Symfony 3.4 and Fixtures Bundle issue with bundle version 3.0
Symfony 3.4.0 Could not find any fixture services to load
Symfony Doctrine can't find fixtures to load
Could not find any fixture services to load - Symfony 3.2
None of the above actually helped me out. That said, this is my configuration:
Composer.json
"require": {
"php": ">=7.0",
"doctrine/doctrine-bundle": "^1.6",
"doctrine/orm": "^2.5",
....
},
"require-dev": {
....
"doctrine/doctrine-fixtures-bundle": "^3.0",
}
I'm using a company-developed Bundle which worked fine until the last version of the above (last tested and working configuration had PHP 5.6, Doctrine bundle ^1.6,doctrine orm ^2.5, fixture bundle ^3.0).
This bundle has some Fixture inside VendorName/BundleName/DataFixtures/ORM, all the fixtures have the following declaration:
Class MyFixture1 extends Fixture implements OrderedFixtureInterface,FixtureInterface, ContainerAwareInterface{
...
}
Inside this bundle there's a services.yml file, loaded by this:
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'));
$loader->load('services.yml');
}
VendorName/BundleName/Resources/config/Services.yml i tried different configurations:
services:
_defaults:
autowire: true
autoconfigure: true
public: false
VendorName\BundleName\:
resource: '../../*'
# you can exclude directories or files but if a service is unused, it's removed anyway
exclude: '../../{Entity,Repository,Tests,EventListener}'
I tried expliciting searching inside DataFixtures:
VendorName/BundleName\DataFixtures\:
resource: '../../src/VendorName/BundleName/DataFixtures'
tags: ['doctrine.fixture.orm']
And even manually configure the service:
VendorName\BundleName\DataFixtures\ORM\MyFixture1:
class: VendorName/BundleNamee\DataFixtures\ORM\MyFixture1
tags: ['doctrine.fixture.orm']
But unfortunately it keeps giving the error. Any idea of what i'm doing wrong? Long time ago it was possible to manually specify to the fixture command which bundle to look in, but now it's not possible anymore
UPDATE 1:
Sorry guys forgot to point the error message: "Could not find any fixture services to load"
The accepted answer helped point me in the right direction to get this working. Though cache could indeed be a problem, having Fixtures in your own bundles does require you to register them.
Using SF 5.1.* I created a services_dev.yaml file and added in:
services:
// other config
Namespace\Registered\In\Composer\For\Fixtures\:
resource: '../vendor/path/registered/in/composer/to/fixtures'
tags: ['doctrine.fixture.orm']
Then indeed, clear cache and it should work.
Added *_dev to the services.yaml file as it's a way for Symfony to only load it in when in your in a dev environment (per APP_ENV Environment variable).
For everyone landing here i solved my problem, what i can tell you is:
Double check you enabled the Bundle in the AppKernel
Clear your symfony cache using the command php bin/console cache:clear --env=dev (or env=prod)
Manually delete cache folder

Symfony combine yaml and php configuration files

In Symfony 4, I would like to combine different configuration files for services. In the following scenario, my attempt is to import services from php configuration named services.php and then perform the other services configurations in the yaml file that imports the others services..
services.yaml
imports:
- { resource: services.php }
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'
services.php
<?php
use Symfony\Component\DependencyInjection\Definition;
$definition = new Definition();
$definition
->setAutowired(true)
->setAutoconfigured(true)
->setPublic(false)
;
$this->registerClasses($definition, 'App\\', '../src/*', '../src/{Entity,Migrations,Tests}');
$container->getDefinition(\App\SomeClass::class)
->setArgument('$param', 'someValue');
Class file
class SomeClass
{
public function __construct(string $param)
{
...
}
I get the following error:
Cannot autowire service
"App\SomeClass": argument "$param"
of method "__construct()" is type-hinted "string", you should
configure its value explicitly.
Also, I'm wondering if I have to necessary to overwrite the initial _defaults definition (or others already done in by the files that imports) from the yaml or I can inherit. Not sure how these files are all merged.
The problem is that you registering the classes in src/* twice, once in your services.php and once in your services.yaml.
So in the first run with services.php you correctly define the class and the required argument, then, in the second run with services.yaml the definition is being overwritten and it loses the argument again.
The minimal solution would be to exclude the SomeClass.php in the services.yaml so it won't be registered a second time:
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests,Kernel.php,SomeClass.php}' # <- here I added SomeClass.php
It would be better though to create a separate namespace and exclude the directory in the YAML and only register this directory in the PHP-config.

Symfony 4 - The autoloader expected class […] to be defined in file

I'm trying to add an old Bundle that I have built on Symfony 3.* to Symfony 4 but I get this error:
The autoloader expected class
"App\SBC\TiersBundle\Controller\ChantierController" to be defined in
file
"/Applications/MAMP/htdocs/Projects/HelloSymfony4/vendor/composer/../../src/SBC/TiersBundle/Controller/ChantierController.php".
The file was found but the class was not in it, the class name or
namespace probably has a typo in
/Applications/MAMP/htdocs/Projects/HelloSymfony4/config/services.yaml
(which is loaded in resource
"/Applications/MAMP/htdocs/Projects/HelloSymfony4/config/services.yaml").
It seems like the framework did not recognise the namespace of the bundle so I did these steps:
In config/bundle.php I added the third line:
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
\SBC\TiersBundle\TiersBundle::class => ['all' => true], // this one
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
];
And in composer.json I added the first line in autoload section:
"autoload": {
"psr-4": {
"SBC\\": "src/SBC/",
"App\\": "src/"
}
},
Because the namespace of my Bundle starts with SBC\, and I have launched composer dump-autoload in the console.
<?php
namespace SBC\TiersBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class TiersBundle extends Bundle
{
}
ChantierController.php:
namespace SBC\TiersBundle\Controller;
use SBC\TiersBundle\Entity\Chantier;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class ChantierController extends Controller
{
...
}
And this is my Bundle under /src:
Unfortunately still facing the same error, how can I fix it and thanks in advance.
UPDATE: config/services.yaml:
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
SBC\:
resource: '../src/SBC/*'
exclude: '../src/SBC/TiersBundle/{Entity,Migrations,Tests}'
SBC\TiersBundle\Controller\:
resource: '../src/SBC/TiersBundle/Controller'
tags: ['controller.service_arguments']
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
The problem is most likely caused by Symfony configuration and conflict in namespaces. First you need to adjust your config/services.yaml:
SBC\:
resource: '../src/SBC/*'
exclude: '../src/SBC/TiersBundle/{Entity,Migrations,Tests,Kernel.php}'
SBC\TiersBundle\Controller\:
resource: '../src/SBC/TiersBundle/Controller'
tags: ['controller.service_arguments']
App\:
resource: '../src/*'
exclude: '../src/{SBC,Entity,Migrations,Tests,Kernel.php}'
This way you'll define defaults for your namespace and prevent the default namespace App to include your directory when generating autoload classes. Note that if you are using annotation routes, you also need to adjust config/routes/annotations.yaml:
sbc_controllers:
resource: ../../src/SBC/TiersBundle/Controller/
type: annotation
so the routes are generated correctly. After performing these steps run composer dump-autoload again and clear Symfony's cache.
This might be helpful in the future if you run into another problems: https://github.com/symfony/symfony/blob/master/UPGRADE-4.0.md

Categories