/** * Connects a controller with multiples routes. * * Usage : * connectRoutes( * 'MyController', * array( * '/foo' => array( * 'action' => 'myAction', * 'param' => '', * 'param' => '', * ... * ) * ) * [, middleware, middleware, ...] * ); * * @param string $controller Controller name, ex. : 'MyController' * @param array $routes List of routes and their parameters * @param callable Globals middlewares, called for each route */ public function connectRoutes($controller, array $routes) { ## get global middlewares if exists if (func_num_args() > 2) { $globalMiddlewares = array_slice(func_get_args(), 2); } ## parse routes foreach ($routes as $pattern => $params) { if (!isset($params['action'])) { throw new \Exception('route action parameter is required'); } ## creates route $methodName = $params['action']; $routeCallable = function () use($controller, $methodName) { $instance = $this->register($controller); return call_user_func_array(array($instance, $methodName), func_get_args()); }; $route = new Route($pattern, $routeCallable); ## binds HTTP methods $params['method'] = isset($params['method']) && is_string($params['method']) ? $params['method'] : 'GET'; $methods = explode('|', $params['method']); foreach ($methods as $m) { $route->via($m); } ## binds route name if (isset($params['name']) && is_string($params['name'])) { $route->name($params['name']); } ## binds route conditions if (isset($params['conditions']) && is_array($params['conditions'])) { $route->conditions($params['conditions']); } ## binds middlewares $middlewares = isset($globalMiddlewares) ? $globalMiddlewares : array(); $middlewares = isset($params['middlewares']) && is_array($params['middlewares']) ? array_merge($middlewares, $params['middlewares']) : $middlewares; if (!empty($middlewares)) { $this->bindMiddlewares($route, $middlewares); } ## map to router $this->_slim->router()->map($route); } }