use*_*082 14 routing caching routes dynamic symfony
我正在尝试创建动态路由,因为我创建了一个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
}
}
Run Code Online (Sandbox Code Playgroud)
然后我为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>
Run Code Online (Sandbox Code Playgroud)
我们需要的最后一件事是/app/config/routing.yml中的一些额外的行:
AcmeRoutingBundle:
resource: .
type: extra
Run Code Online (Sandbox Code Playgroud)
我研究并尝试了一下,发现您可以删除以下文件:
对于开发人员:
/app/cache/dev/appDevUrlGenerator.php
/app/cache/dev/appDevUrlGenerator.php.meta
/app/cache/dev/appDevUrlMatcher.php
/app/cache/dev/appDevUrlMatcher.php.meta
Run Code Online (Sandbox Code Playgroud)
对于产品:
/app/cache/prod/appProdUrlGenerator.php
/app/cache/prod/appProdUrlMatcher.php
Run Code Online (Sandbox Code Playgroud)
这样做只有一个小缺点。我正在使用当前路线来确定菜单项是否处于活动状态:
{% set currentPath = path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) %}
...
<li{% if currentPath == path('mybundle_default_index') %} class="active"{% endif %}>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,app.request.attributes.get('_route')
仍然被缓存为可能不再存在的路由。我还不知道这是否只涉及树枝缓存或其他部分。
另外我不明白为什么你必须在每次页面加载时删除整个缓存?您只需在添加新路由时清除缓存即可。
归档时间: |
|
查看次数: |
2913 次 |
最近记录: |