简体   繁体   中英

zend framework 2 + custom routing

I tried to follow the recommendations from this topic: zend framework 2 + routing database

I have a route class:

    namespace Application\Router;

use Zend\Mvc\Router\Http\RouteInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\Mvc\Router\RouteMatch;

class Content implements RouteInterface, ServiceLocatorAwareInterface {

protected $defaults = array();
protected $routerPluginManager = null;

public function __construct(array $defaults = array()) {
    $this->defaults = $defaults;
}

public function setServiceLocator(\Zend\ServiceManager\ServiceLocatorInterface $routerPluginManager) {
    $this->routerPluginManager = $routerPluginManager;
}

public function getServiceLocator() {
    return $this->routerPluginManager;
}

public static function factory($options = array()) {
    if ($options instanceof \Traversable) {
        $options = ArrayUtils::iteratorToArray($options);
    } elseif (!is_array($options)) {
        throw new InvalidArgumentException(__METHOD__ . ' expects an array or Traversable set of options');
    }

    if (!isset($options['defaults'])) {
        $options['defaults'] = array();
    }

    return new static($options['defaults']);
}

public function match(Request $request, $pathOffset = null) {
    if (!method_exists($request, 'getUri')) {
        return null;
    }

    $uri = $request->getUri();
    $fullPath = $uri->getPath();

    $path = substr($fullPath, $pathOffset);
    $alias = trim($path, '/');

    $options = $this->defaults;
    $options = array_merge($options, array(
        'path' => $alias
            ));

    return new RouteMatch($options);
}

public function assemble(array $params = array(), array $options = array()) {
    if (array_key_exists('path', $params)) {
        return '/' . $params['path'];
    }

    return '/';
}

public function getAssembledParams() {
    return array();
}

}

Pay attention that the match() function returns object of the instance of Zend\\Mvc\\Router\\RouteMatch However in the file Zend\\Mvc\\Router\\Http\\TreeRouteStack it checks for object to be the instance of RouteMatch (without prefix of namespace)

if (
    ($match = $route->match($request, $baseUrlLength, $options)) instanceof RouteMatch
            && ($pathLength === null || $match->getLength() === $pathLength)
        )

And the condition fails in my case because of the namespace.

Any suggestions?

Ok, i figured out what the problem was. Instead of returning Zend\\Mvc\\Router\\RouteMatch I should return Zend\\Mvc\\Router\\Http\\RouteMatch

This fixed my problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM