2

试图找到解决方案,但我总是卡在文档或答案中包括其他捆绑包。在动态路由器的文档中,您可以找到提示:

“当然,你也可以有几个参数,就像普通的 Symfony 路由一样。模式、默认值和要求的语义和规则与核心路由完全相同。”

而已。

...

/foo/{id}/bar

我尝试了(似乎没有)一切来完成它。

所有尝试都相同:

我尝试过应用变量模式和子路由。

use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\Route as PhpcrRoute;

$dm = $this->get('cmf_routing.route_provider');

$route = new PhpcrRoute();
$route->setPosition( $dm->find( null, '/cms/routes' ), 'foo' );
$route->setVariablePattern('/{id}');
$dm->persist( $route );

$child = new PhpcrRoute();
$child->setPosition( $route, 'bar' );
$dm->persist( $child );

$dm->flush();

有或没有默认值和要求只有'/foo/bar''/foo/*'返回匹配,但'/foo/1/bar'提示我“没有找到“GET /foo/1/bar 的路由” “”。

...

刚才我几乎完成了。

use Symfony\Cmf\Bundle\RoutingBundle\Doctrine\Phpcr\Route as PhpcrRoute;

$dm = $this->get('cmf_routing.route_provider');

$route = new PhpcrRoute();
$route->setPosition( $dm->find( null, '/cms/routes' ), 'example_route' );
$dm->persist( $route );

$route->setPrefix( '/cms/routes/example_route' );
$route->setPath( '/foo/{id}/bar' );

$dm->flush();

如果前缀是'/cms/routes'并且名称是'foo'一切正常。但既然我已经走到了这一步,指定一个说话的名字就会把它四舍五入。

谢谢指教!

4

1 回答 1

1

实际上,您已经非常接近解决方案了!

使用 PHPPCR-ODM 时,路由文档 id 是它在存储库中的路径。PHPPCR 将所有内容存储在树中,因此每个文档都需要位于树中的特定位置。然后我们使用前缀来获取要匹配的 URL。如果前缀配置为 /cms/routes 并且请求是针对 /foo 的,则路由器会在 /cms/routes/foo 中查找。要允许参数,您可以setVariablePattern按照正确的假设使用。对于 /foo/{id}/bar 的用例,你需要做setVariablePattern('/{id}/bar'). 你也可以有setVariablePattern('/{context}/{id}')(这就是你引用的文档段落的意思——我会考虑在那里添加一个例子,因为说“你可以做到这一点”但不解释如何做到这一点确实没有帮助)。

setPath不建议调用,因为它不太明确 - 但正如您所注意到的,它可以完成工作。查看 phpdoc 和 Model\Route::setPattern 的实现:

/**
 * It is recommended to use setVariablePattern to just set the part after
 * the static part. If you use this method, it will ensure that the
 * static part is not changed and only change the variable part.
 *
 * When using PHPCR-ODM, make sure to persist the route before calling this
 * to have the id field initialized.
 */
public function setPath($pattern)
{
    $len = strlen($this->getStaticPrefix());

    if (strncmp($this->getStaticPrefix(), $pattern, $len)) {
        throw new \InvalidArgumentException('You can not set a pattern for the route that does not start with its current static prefix. First update the static prefix or directly use setVariablePattern.');
    }

    return $this->setVariablePattern(substr($pattern, $len));
}

关于显式名称:在示例中,存储库路径也是路由的名称/cms/routes/foo。但是在代码中使用动态路由的路由名称并不是一个好主意,因为这些路由应该可以由管理员编辑(和删除)。如果你有一个确定存在并且在特定路径的路由,使用配置的 symfony 路由(routing.yml文件)。如果是动态路由,请查看CMF Resource Bundle。它允许定义一个角色获取文档以及按角色查找文档的方法。如果您想从控制器/模板链接到具有特定角色的路由,这就是要走的路。如果您有一个与路由文档链接的内容文档并且该内容文档可用,那么您的第三个也是最好的选择是从内容文档生成 URL。CMF 动态路由器可以做到这一点,只需使用您通常指定路由名称的内容对象。

于 2015-10-01T06:27:50.120 回答