服务未找到“\ServiceLocator”内的容器是一个较小的服务定位器,只知道“内核”

问题描述 投票:0回答:1

因为我希望我的应用程序遵循某种 DDD 结构,所以我希望我的控制器、实体、存储库、表单等位于特定目录中。例如:src/Appication/Dealer/Controller/DealerController.php

为了加载这个控制器,我创建了一个路由服务:src/Routing/ApplicationLoader.php。如果我在测试脚本中运行它,效果很好。它为我提供了经销商控制器中可用的路线列表。

但是 symfony 给了我这个:

Service "@App\Routing\ApplicationLoader" not found: the container inside "Symfony\Component\DependencyInjection\Argument\ServiceLocator" is a smaller service locator that only knows about the "kernel" and "security.route_loader.logout" services in @App\Routing\ApplicationLoader (which is being imported from "/var/www/html/config/routes.yaml"). Make sure the "App\Routing\ApplicationLoader" bundle is correctly registered and loaded in the application kernel class. If the bundle is registered, make sure the bundle path "@App\Routing\ApplicationLoader" is not empty.

它甚至没有击中

ApplicationLoader.php
(通过添加出口进行测试)

我怎样才能让 symfony 了解它需要加载我的脚本? ;)

(我认为我的路线和服务是正确的 - 见下文)

要测试这一点,只需创建一个干净的 symfony 安装,使用制造商创建一个实体和一个 CRUD,创建目录结构: src/应用程序/%entityName%/

  • 控制器/
  • 实体/
  • 存储库/
  • 表格/

并将相应的文件放在那里。 然后根据下面的内容修改services和routes.yaml,并将ApplicationLoader.php放在src/Routing文件夹中。

这是我的

services.yaml

parameters:

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: false      # Automatically injects dependencies in your services.
        autoconfigure: false # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones
    App\Routing\ApplicationLoader:
        public: true
        arguments:
            $controllerDirectory: '%kernel.project_dir%/src/Application'
        tags:
            - { name: 'router.loader', priority: 0 }

这是我的

routes.yaml

# Handles routes for generic controllers in src/Controller/

controllers:
resource:
path: ../src/Controller/
namespace: App\Controller
type: attribute

# Handles custom routes for controllers under src/Application

custom_routes:
resource: '@App\Routing\ApplicationLoader'
type: service

这是我的

ApplicationLoader.php
:

<?php

namespace App\Routing;

use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Finder\Finder;
use ReflectionClass;

class ApplicationLoader extends Loader
{
private bool $isLoaded = false;

    private string $controllerDirectory;
    
    public function __construct(string $controllerDirectory)
    {
        $this->controllerDirectory = $controllerDirectory;
    }
    
    public function load($resource, ?string $type = null): RouteCollection
    {
    
        error_log("Loading resource: $resource with type: $type");
        if (true === $this->isLoaded) {
            throw new \RuntimeException('Do not add the "application" loader twice');
        }
    
        $routes = new RouteCollection();
    
        // Use Symfony Finder to scan the directory for controllers
        $finder = new Finder();
        $finder->files()->in($this->controllerDirectory)->name('*Controller.php');
    
        // Iterate through controller files and add routes
        foreach ($finder as $file) {
            $className = $this->getClassNameFromFile($file);
            error_log("Processing controller: $className");
    
            $reflectionClass = new ReflectionClass($className);
    
            // Check if the class has route annotations or attributes
            if ($reflectionClass->isSubclassOf('Symfony\Bundle\FrameworkBundle\Controller\AbstractController')) {
                $this->addRoutesFromAttributes($reflectionClass, $routes);
            }
        }
    
        return $routes;
    }
    
    public function supports($resource, ?string $type = null): bool
    {
        error_log("Checking support for resource: $resource with type: $type");
    
        return 'service' === $type;
    }
    
    private function getClassNameFromFile($file): string
    {
        // Resolve the absolute path of the controller directory
        $controllerDirectoryRealPath = realpath($this->controllerDirectory);
    
        // Resolve the file's real path
        $fileRealPath = $file->getRealPath();
    
        // Calculate the relative path by removing the base directory
        $relativePath = substr($fileRealPath, strlen($controllerDirectoryRealPath) + 1);
    
        // Normalize directory separators to backslashes for namespaces
        $relativePath = str_replace(DIRECTORY_SEPARATOR, '\\', $relativePath);
    
        // Remove the file extension (.php) and prepend the base namespace
        return 'App\Application\' . str_replace('.php', '', $relativePath);
    }
    
    private function addRoutesFromAttributes(\ReflectionClass $reflectionClass, RouteCollection $routes): void
    {
        // Check the class-level attributes for the base path (e.g., #[Route('/dealer')])
        $classAttributes = $reflectionClass->getAttributes(\Symfony\Component\Routing\Attribute\Route::class);
        $classBasePath = '';
    
        foreach ($classAttributes as $classAttribute) {
            $classRoute = $classAttribute->newInstance();
            $classBasePath = $classRoute->getPath();
        }
    
        // Iterate through each method to find route attributes
        foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
            // Ignore inherited methods from AbstractController
    
            // Skip methods from parent classes
            if ($method->getDeclaringClass()->getName() !== $reflectionClass->getName()) {
                continue;
            }
    
            // Get method attributes for routes
            $methodAttributes = $method->getAttributes(\Symfony\Component\Routing\Attribute\Route::class);
    
            foreach ($methodAttributes as $methodAttribute) {
    
                $methodRoute = $methodAttribute->newInstance();
    
                // Combine the class-level base path and the method-level path
                $fullPath = rtrim($classBasePath, '/') . '/' . ltrim($methodRoute->getPath() ?? '', '/');
    
                // Add the route to the collection
                $routes->add(
                    $methodRoute->getName(),
                    new Route(
                        $fullPath,
                        ['_controller' => $reflectionClass->getName() . '::' . $method->getName()],
                        [],        // Default requirements
                        [],        // Default options
                        '',        // Host
                        [],        // Schemes
                        $methodRoute->getMethods()
                    )
                );
            }
        }
    }

}

这是我的

test.php
脚本,位于/public

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use App\\Routing\ApplicationLoader;
use Symfony\Component\Routing\RouteCollection;

try {
// Define the directory where your Application controllers are located
$controllerDirectory = __DIR__ . '/../src/Application';

    // Instantiate your ApplicationLoader with the specified directory
    $loader = new ApplicationLoader($controllerDirectory);
    
    // Invoke the loader to load routes
    $routes = $loader->load(null, 'service');
    
    // Display loaded routes
    echo "Loaded Routes:\n";
    foreach ($routes as $name => $route) {
        echo " - $name: " . $route->getPath() . "<br/>";
        echo "   Controller: " . $route->getDefault('_controller') . "<br/>";
        echo "   Methods: " . implode(', ', $route->getMethods()) . "<br/><br/>";
    }

} catch (Throwable $e) {
// Catch and display errors for debugging
echo "Error: " . $e-\>getMessage() . "\<br/\>";
echo $e-\>getTraceAsString() . "\<br/\>";
}

请帮忙;)

php routes domain-driven-design autoload symfony7
1个回答
0
投票

好的,答案实际上要简单得多,我想要的实际上可以通过将 paths.yaml 更改为:

标准控制器(保持其正常工作)控制器:

resource:
    path: ../src/Controller/
    namespace: App\Controller
type: attribute

所有应用程序路由 - 这将扫描应用程序 application_routes 下的所有 */Controller 目录:

resource:
    path: ../src/Application/
    namespace: App\Application
type: attribute

保留 services.yaml 原来的样子,并将 config/packages/doctrine.yaml 中的映射部分更改为:

    mappings:
        Default:
            is_bundle: false
            type: attribute
            dir: '%kernel.project_dir%/src/Entity'
            prefix: 'App\Entity'
            alias: Default
        Controller:
            is_bundle: false
            type: attribute
            dir: '%kernel.project_dir%/src/Controller'
            prefix: 'App\Controller'
            alias: Controller
        Application:
            is_bundle: false
            type: attribute
            dir: '%kernel.project_dir%/src/Application'
            prefix: 'App\Application'
            alias: Application

这样,不仅会加载“src/Controller”中的应用程序,还会加载“src/Application/MyApp/Controller”中的所有内容

© www.soinside.com 2019 - 2024. All rights reserved.