【问题标题】:How to generate an URL for a controller in Symfony?如何在 Symfony 中为控制器生成 URL?
【发布时间】:2020-04-14 16:47:12
【问题描述】:

我知道如何为路由生成 URL。但是现在我需要为控制器或带有方法的控制器生成 URL。我检查了UrlGenerator的来源,但没有找到任何相关信息。 Symfony 文档中也没有任何信息。

控制器的方法有一个关联的url。此 url 将在控制器中使用,但我需要生成器作为服务。

【问题讨论】:

  • 控制器的方法有关联的url吗?还是不通过 HTTP 公开?谁需要使用此网址?可以成为一名优秀的内线前锋吗?
  • @Matteo 我更新了这个问题。但我不明白这个“内线前锋可以吗?”
  • 您应该提供一些额外的信息来澄清您的问题,例如控制器和路由(注释或 yaml 或其他)的样子
  • 重点是你的问题对我们来说有点奇怪。所以我只想了解你的问题,但如果你不想更新你的问题,那么我也可以;-)
  • 问题是,控制器没有“路由”。或者甚至可能有不止一条路线指向它们。一个控制器类可能有多个通过不同路由公开的公共方法,没有明确的一对一关系。因此,您最多只能搜索加载的路由集合,以查看任何配置的路由是否在其“默认值”中具有该 class::method()。

标签: symfony symfony-routing


【解决方案1】:

基本上你需要:

1。向控制器添加路由

<?php

declare(strict_types=1);

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

final class BlogController extends AbstractController
{
    /**
     * @Route(path="blog", name="blog")
     */
    public function __invoke(): Response
    {
        return $this->render('blog/blog.twig');
    }
}

2。为路由生成url路由

Symfony docs

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SomeService
{
    /**
     * @var UrlGeneratorInterface
     */
    private $urlGenerator;

    public function __construct(UrlGeneratorInterface $urlGenerator)
    {
        $this->urlGenerator = $urlGenerator;
    }

    public function go()
    {
        // ...

        // generate a URL with no route arguments
        $signUpPage = $this->urlGenerator->generateUrl('sign_up');

        // generate a URL with route arguments
        $userProfilePage = $this->urlGenerator->generateUrl('user_profile', [
            'username' => $user->getUsername(),
        ]);


        // generated URLs are "absolute paths" by default. Pass a third optional
        // argument to generate different URLs (e.g. an "absolute URL")
        $signUpPage = $this->urlGenerator->generateUrl('sign_up', [], UrlGeneratorInterface::ABSOLUTE_URL);

        // when a route is localized, Symfony uses by default the current request locale
        // pass a different '_locale' value if you want to set the locale explicitly
        $signUpPageInDutch = $this->urlGenerator->generateUrl('sign_up', ['_locale' => 'nl']);
    }
}

【讨论】:

  • 感谢您的建议,但我看不出它对我有什么帮助。您只需使用 UrlGenerator。我需要这样的东西:$generator-&gt;controllerUrl(\App\MyController::class, 'methodWithRoute').
  • 我理解了这个问题。那是不可能的。您需要使用路线名称来做到这一点
【解决方案2】:

所以,这里是服务。至少是一个如何实施的例子。 SF4

namespace App\Route;

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RouterInterface;

class UrlGenerator
{
    /**
     * @var RouteCollection
     */
    private $collection;

    public function __construct(RouterInterface $router)
    {
        $this->collection = $router->getRouteCollection();
    }

    public function generate(string $controllerClass, string $method): string
    {
        foreach ($this->collection as $item) {
            $defaults = $item->getDefaults();
            $controllerPath = $defaults['_controller'];
            $parts = explode('::', $controllerPath);

            if ($parts[0] !== $controllerClass) {
                continue;
            }

            if ($parts[1] !== $method) {
                continue;
            }

            return $item->getPath();
        }

        throw new \RuntimeException(
            'Route for such combination of controller and method is absent'
        );
    }
}

测试不佳但有效的解决方案。

【讨论】:

    猜你喜欢
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    相关资源
    最近更新 更多