php8.5
Home/ Manual/ yaf / yaf_route_interface/ Yaf_Route_Interface::route

Yaf_Route_Interface::route

PHP function Edit on GitHub ✎

(Yaf >=1.0.0)

Route a request

Description

Yaf_Route_Interface::route(Yaf_Request_Abstract $request): bool

Yaf_Route_Interface::route is the only method that a custom route should implement.

Note

since of 2.3.0, there is another method should also be implemented, see Yaf_Route_Interface::assemble.

if this method return true, then the route process will be end. otherwise, Yaf_Router will call next route in the route stack to route request.

This method would set the route result to the parameter request, by calling Yaf_Request_Abstract::setControllerName, Yaf_Request_Abstract::setActionName and Yaf_Request_Abstract::setModuleName.

This method should also call Yaf_Request_Abstract::setRouted to make the request routed at last.

Parameters

request

A Yaf_Request_Abstract instance.

Return Values

Examples

Yaf_Route_Interface::route example

php
<?php
class ApiRoute implements Yaf_Route_Interface {

    private $_prefix;

    public function __construct(string $prefix) {
        $this->_prefix = $prefix;
    }

    public function route(Yaf_Request_Abstract $request): bool {
        $uri = $request->getRequestUri();
        if (0 !== strpos($uri, $this->_prefix)) {
            /* not our business, let the router try the next route */
            return false;
        }

        /* parse the URI "/api/user/list" into controller/action */
        $segments = explode("/", ltrim(substr($uri, strlen($this->_prefix)), "/"));
        $controller = isset($segments[0]) ? ucfirst($segments[0]) : NULL;
        $action = isset($segments[1]) ? $segments[1] : NULL;

        if (empty($controller)) {
            return false;
        }

        $request->setModuleName("index");
        $request->setControllerName($controller);
        $request->setActionName($action);
        $request->setRouted(); /* the route process ends here */

        return true;
    }

    public function assemble(array $info, ?array $query = null): string {
        $uri = $this->_prefix . "/" . strtolower($info[':c']);
        if (isset($info[':a'])) {
            $uri .= "/" . $info[':a'];
        }

        if (!empty($query)) {
            $uri .= "?" . http_build_query($query);
        }

        return $uri;
    }
}

/**
 * register the custom route
 */
Yaf_Dispatcher::getInstance()->getRouter()->addRoute("api", new ApiRoute("/api"));
?>

The above example will output something similar to:

output
/* http://yourdomain.com/api/user/list
 * routes to the following values:
 */
array(
  "module"     => "index",
  "controller" => "User",
  "action"     => "list",
)

See Also

  • Yaf_Route_Interface::assemble
  • Yaf_Router::addRoute
  • Yaf_Request_Abstract::setRouted

Source: reference/yaf/yaf_route_interface/route.xml · from the official PHP manual (php/doc-en)