我正在尝试创建动态路由,因为我创建了一个 CMS,其中创建的每个页面都可以关联到一个路由。我正在使用此链接中的示例 - http://php-and-symfony.matthiasnoback.nl/2012/01/symfony2-dynamically-add-routes/一切正常,但是路由被缓存,因此只有一条路线会工作,但除非我清除缓存,否则下一个不会。是否可以在此阶段仅删除路由缓存,还是有其他选择?我不想在每个页面加载时删除整个缓存目录,因为那没有意义。这是示例代码:
namespace Acme\RoutingBundle\Routing;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class ExtraLoader implements LoaderInterface
{
private $loaded = false;
public function load($resource, $type = null)
{
if (true === $this->loaded) {
throw new \RuntimeException('Do not add this loader twice');
}
$routes = new RouteCollection();
$pattern = '/extra';
$defaults = array(
'_controller' => 'AcmeRoutingBundle:Demo:extraRoute',
);
$route = new Route($pattern, $defaults);
$routes->add('extraRoute', $route);
return $routes;
}
public function supports($resource, $type = null)
{
return 'extra' === $type;
}
public function getResolver()
{
}
public function setResolver(LoaderResolver $resolver)
{
// irrelevant to us, since we don't need a resolver
}
}
然后我为 ExtraLoader 做了一个服务:
<!-- in /src/Acme/RoutingBundle/Resources/config/services.xml -->
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="acme.routing_loader" class="Acme\RoutingBundle\Routing\ExtraLoader">
<tag name="routing.loader"></tag>
</service>
</services>
</container>
我们需要的最后一件事是在 /app/config/routing.yml 中增加几行:
AcmeRoutingBundle:
resource: .
type: extra