0

I'm writing my custom router for a Zend Framework 2 project extending Zend\Mvc\Router\RouteInterface. The routes should come from a database (large project with hundreds of pages). A working Router obviously only needs two methods: match() and assemble(). The match one I got working alright.

But what about assemble()? What should this method return? Could it be it only returns the base path of the Application?

Here is what one of the internal routers (Zend\Mvc\Router\SimpleRouteStack) of ZF2 does:

/**
 * assemble(): defined by RouteInterface interface.
 *
 * @see    \Zend\Mvc\Router\RouteInterface::assemble()
 * @param  array $params
 * @param  array $options
 * @return mixed
 * @throws Exception\InvalidArgumentException
 * @throws Exception\RuntimeException
 */
public function assemble(array $params = array(), array $options = array())
{
    if (!isset($options['name'])) {
        throw new Exception\InvalidArgumentException('Missing "name" option');
    }

    $route = $this->routes->get($options['name']);

    if (!$route) {
        throw new Exception\RuntimeException(sprintf('Route with name "%s" not found', $options['name']));
    }

    unset($options['name']);

    return $route->assemble(array_merge($this->defaultParams, $params), $options);
}

Reference: Custom Routing in Zend Framework 2

4

1 回答 1

1

基本上 assemble 是当你做类似的事情时会调用的$this->redirect-toRoute($name, $params);

所以它应该根据路由配置返回一个 URL 字符串。该路由可以使用相同的路由配置进行匹配。

当您调用 toRoute 时,您发布的路由堆栈会找到您在调用中指定的名称的路由,然后要求它组装该路由的 URL

'test' => array(
    'type'    => 'Segment',
    'options' => array(
        'route'    => '/test[/:id]',
        'constraints' => array(
            'id'     => '[a-zA-Z][a-zA-Z0-9_-]*',
        ),
        'defaults' => array(
            '__NAMESPACE__' => 'Application\Controller',
        ),
    ),
),

当我们调用$this->redirect-toRoute('test', array('id' => 1));路由堆栈时,这条名为 'test' 的路由会找到 'test' 的实例化路由,这是一个 \Zend\Mvc\Router\Http\Segment 然后调用它的 assemble 函数,该函数将在调用 toRoute 它将产生一个这样的 URL 字符串

/测试/1

这基本上就是 assemble 函数的作用。

于 2015-02-08T19:52:13.593 回答