最近我在我们需要的一个功能上碰壁了——路由。
我们应用程序中的路由是静态的,但根据环境的不同,url 会有所不同。默认情况下,Symfony 基于 RouteLoaders 和 RouteCollections 生成路由,然后将其存储在缓存中,这使得基于 envs 更改 url 有点问题。
有没有办法将路由添加到路由器after但before它被使用以便我可以注入我的路由,我的环境已经从正确的环境加载?
您可以使用php路由配置格式动态配置您的路由,或者您可以覆盖
loadRoutes
中的Kernel.php
方法。
1。覆盖 loadRoutes 方法
// src/Kernel.php
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class Kernel extends BaseKernel
{
use MicroKernelTrait {
loadRoutes as protected loadRoutesKernel;
}
public function loadRoutes(LoaderInterface $loader): RouteCollection
{
// Loading existing routes
$collection = $this->loadRoutesKernel($loader);
// you condition with some param, example form $_ENV or $this->getContainer()->getParameter('some_param')
$collection->add('dynamic-route', new Route('/docs/test', [
'_controller' => [
SomeController::class, 'test'
]
]));
return $collection;
}
}
这样你就可以根据某些情况动态调整你的路线 环境设置。
2。使用php格式的路由配置
创建一个 routes.php 文件并根据您的要求描述可能的路线场景。
// config/routes.php
use App\Controller\SomeController;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
return function (RoutingConfigurator $routes) {
// your condition
$routes->add('catalog_list', '/catalog/list')
->controller([SomeController::class, 'someAction'])
;
};