【Laravel3.0.0源码阅读分析】路由控制器类router.php

<?php namespace Laravel\Routing;

use Closure;
use Laravel\Str;
use Laravel\Bundle;
use Laravel\Request;

class Router {

	/**
	 * The route names that have been matched.
	 * 已匹配的路由名称。
	 * @var array
	 */
	public static $names = array();

	/**
	 * The actions that have been reverse routed.
	 * 已反向路由的操作。
	 * @var array
	 */
	public static $uses = array();

	/**
	 * All of the routes that have been registered.
	 * 所有已注册的路由。
	 * @var array
	 */
	public static $routes = array();

	/**
	 * All of the "fallback" routes that have been registered.
	 * 所有已注册的“后备”路由。
	 * @var array
	 */
	public static $fallback = array();

	/**
	 * The current attributes being shared by routes.
     * 路由共享的当前属性。
	 */
	public static $group;

	/**
	 * The "handes" clause for the bundle currently being routed.
	 * 当前正在路由的包的“handes”子句。
	 * @var string
	 */
	public static $bundle;

	/**
	 * The number of URI segments allowed as method arguments.
	 * 允许作为方法参数的 URI 段数。
	 * @var int
	 */
	public static $segments = 5;

	/**
	 * The wildcard patterns supported by the router.
	 * 路由器支持的通配符模式。
	 * @var array
	 */
	public static $patterns = array(
		'(:num)' => '([0-9]+)',
		'(:any)' => '([a-zA-Z0-9\.\-_%]+)',
		'(:all)' => '(.*)',
	);

	/**
	 * The optional wildcard patterns supported by the router.
	 *  路由器支持的可选通配符模式。
	 * @var array
	 */
	public static $optional = array(
		'/(:num?)' => '(?:/([0-9]+)',
		'/(:any?)' => '(?:/([a-zA-Z0-9\.\-_%]+)',
		'/(:all?)' => '(?:/(.*)',
	);

	/**
	 * An array of HTTP request methods.
	 * 一组 HTTP 请求方法。
	 * @var array
	 */
	public static $methods = array('GET', 'POST', 'PUT', 'DELETE');

	/**
	 * Register a HTTPS route with the router.
	 * 向路由器注册 HTTPS 路由。
	 * @param  string        $method
	 * @param  string|array  $route
	 * @param  mixed         $action
	 * @return void
	 */
	public static function secure($method, $route, $action)
	{
		$action = static::action($action);

		$action['https'] = true;

		static::register($method, $route, $action);
	}

	/**
	 * Register many request URIs to a single action.
	 * 将多个请求 URI 注册到单个操作。
	 * <code>
	 *		// Register a group of URIs for an action
	 *		Router::share(array('GET', '/'), array('POST', '/'), 'home@index');
	 * </code>
	 *
	 * @param  array  $routes
	 * @param  mixed  $action
	 * @return void
	 */
	public static function share($routes, $action)
	{
		foreach ($routes as $route)
		{
			static::register($route[0], $route[1], $action);
		}
	}

	/**
	 * Register a group of routes that share attributes.
	 * 注册一组共享属性的路由。
	 * @param  array    $attributes
	 * @param  Closure  $callback
	 * @return void
	 */
	public static function group($attributes, Closure $callback)
	{
		// Route groups allow the developer to specify attributes for a group
		// of routes. To register them, we'll set a static property on the
		// router so that the register method will see them.
        // 路由组允许开发人员为一组路由指定属性。 为了注册它们,我们将在路由器上设置一个静态属性,以便注册方法可以看到它们。
		static::$group = $attributes;

		call_user_func($callback);

		// Once the routes have been registered, we want to set the group to
		// null so the attributes will not be assigned to any of the routes
		// that are added after the group is declared.
        // 一旦注册了路由,我们希望将组设置为 null,这样属性就不会分配给在声明组后添加的任何路由。
		static::$group = null;
	}

	/**
	 * Register a route with the router.
	 * 向路由器注册路由。
	 * <code>
	 *		// Register a route with the router
	 *		Router::register('GET' ,'/', function() {return 'Home!';});
	 *
	 *		// Register a route that handles multiple URIs with the router
	 *		Router::register(array('GET', '/', 'GET /home'), function() {return 'Home!';});
	 * </code>
	 *
	 * @param  string        $method
	 * @param  string|array  $route
	 * @param  mixed         $action
	 * @return void
	 */
	public static function register($method, $route, $action)
	{
		if (is_string($route)) $route = explode(', ', $route);

		foreach ((array) $route as $uri)
		{
			// If the URI begins with a splat, we'll call the universal method, which
			// will register a route for each of the request methods supported by
			// the router. This is just a notational short-cut.
            // 如果 URI 以 splat 开头,我们将调用通用方法,该方法将为路由器支持的每个请求方法注册一个路由。 这只是一个符号的捷径。
			if ($method == '*')
			{
				foreach (static::$methods as $method)
				{
					static::register($method, $route, $action);
				}

				continue;
			}

			$uri = str_replace('(:bundle)', static::$bundle, $uri);

			// If the URI begins with a wildcard, we want to add this route to the
			// array of "fallback" routes. Fallback routes are always processed
			// last when parsing routes since they are very generic and could
			// overload bundle routes that are registered.
            // 如果 URI 以通配符开头,我们希望将此路由添加到“回退”路由数组。
            // 解析路由时,回退路由总是最后处理,因为它们非常通用,并且可能会使注册的捆绑路由过载。
			if ($uri[0] == '(')
			{
				$routes =& static::$fallback;
			}
			else
			{
				$routes =& static::$routes;
			}

			// If the action is an array, we can simply add it to the array of
			// routes keyed by the URI. Otherwise, we will need to call into
			// the action method to get a valid action array.
            // 如果 action 是一个数组,我们可以简单地将它添加到由 URI 键控的路由数组中。
            // 否则,我们将需要调用 action 方法来获取有效的 action 数组。
			if (is_array($action))
			{
				$routes[$method][$uri] = $action;
			}
			else
			{
				$routes[$method][$uri] = static::action($action);
			}
			
			// If a group is being registered, we'll merge all of the group
			// options into the action, giving preference to the action
			// for options that are specified in both.
            // 如果正在注册一个组,我们会将所有组选项合并到操作中,为在两者中指定的选项优先考虑操作。
			if ( ! is_null(static::$group))
			{
				$routes[$method][$uri] += static::$group;
			}

			// If the HTTPS option is not set on the action, we'll use the
			// value given to the method. The secure method passes in the
			// HTTPS value in as a parameter short-cut.
            // 如果未在操作上设置 HTTPS 选项,我们将使用为该方法提供的值。 安全方法将 HTTPS 值作为参数快捷方式传入。
			if ( ! isset($routes[$method][$uri]['https']))
			{
				$routes[$method][$uri]['https'] = false;
			}
		}
	}

	/**
	 * Convert a route action to a valid action array.
	 * 将路由操作转换为有效的操作数组。
	 * @param  mixed  $action
	 * @return array
	 */
	protected static function action($action)
	{
		// If the action is a string, it is a pointer to a controller, so we
		// need to add it to the action array as a "uses" clause, which will
		// indicate to the route to call the controller.
        // 如果动作是字符串,则它是指向控制器的指针,因此我们需要将其作为“uses”子句添加到动作数组中,这将指示路由调用控制器。
		if (is_string($action))
		{
			$action = array('uses' => $action);
		}
		// If the action is a Closure, we will manually put it in an array
		// to work around a bug in PHP 5.3.2 which causes Closures cast
		// as arrays to become null. We'll remove this.
        // 如果操作是闭包,我们将手动将其放入数组中以解决 PHP 5.3.2 中导致闭包转换为数组变为空的错误。 我们将删除它。
		elseif ($action instanceof Closure)
		{
			$action = array($action);
		}

		return (array) $action;
	}

	/**
	 * Register a secure controller with the router.
	 * 向路由器注册一个安全控制器。
	 * @param  string|array  $controllers
	 * @param  string|array  $defaults
	 * @return void
	 */
	public static function secure_controller($controllers, $defaults = 'index')
	{
		static::controller($controllers, $defaults, true);
	}

	/**
	 * Register a controller with the router.
	 * 向路由器注册控制器。
	 * @param  string|array  $controller
	 * @param  string|array  $defaults
	 * @param  bool          $https
	 * @return void
	 */
	public static function controller($controllers, $defaults = 'index', $https = false)
	{
		foreach ((array) $controllers as $identifier)
		{
			list($bundle, $controller) = Bundle::parse($identifier);

			// First we need to replace the dots with slashes in thte controller name
			// so that it is in directory format. The dots allow the developer to use
			// a cleaner syntax when specifying the controller. We will also grab the
			// root URI for the controller's bundle.
            // 首先,我们需要将控制器名称中的点替换为斜线,以便它采用目录格式。
            // 这些点允许开发人员在指定控制器时使用更简洁的语法。 我们还将获取控制器包的根 URI。
			$controller = str_replace('.', '/', $controller);

			$root = Bundle::option($bundle, 'handles');

			// If the controller is a "home" controller, we'll need to also build a
			// index method route for the controller. We'll remove "home" from the
			// route root and setup a route to point to the index method.
            // 如果控制器是“home”控制器,我们还需要为控制器构建一个索引方法路由。
            // 我们将从路由根中删除“home”并设置一个指向 index 方法的路由。
			if (ends_with($controller, 'home'))
			{
				static::root($identifier, $controller, $root);
			}

			// The number of method arguments allowed for a controller is set by a
			// "segments" constant on this class which allows for the developer to
			// increase or decrease the limit on method arguments.
            // 控制器允许的方法参数数量由此类上的“段”常量设置,允许开发人员增加或减少方法参数的限制。
			$wildcards = static::repeat('(:any?)', static::$segments);

			// Once we have the path and root URI we can build a simple route for
			// the controller that should handle a conventional controller route
			// setup of controller/method/segment/segment, etc.
            // 一旦我们有了路径和根 URI,我们就可以为控制器构建一个简单的路由,该路由应该处理控制器/方法/段/段等的常规控制器路由设置。
			$pattern = trim("{$root}/{$controller}/{$wildcards}", '/');

			// Finally we can build the "uses" clause and the attributes for the
			// controller route and register it with the router with a wildcard
			// method so it is available on every request method.
            // 最后,我们可以为控制器路由构建“uses”子句和属性,并使用通配符方法将其注册到路由器,以便它可用于每个请求方法。
			$uses = "{$identifier}@(:1)";

			$attributes = compact('uses', 'defaults', 'https');

			static::register('*', $pattern, $attributes);
		}
	}

	/**
	 * Register a route for the root of a controller.
	 * 为控制器的根注册一个路由。
	 * @param  string  $identifier
	 * @param  string  $controller
	 * @param  string  $root
	 * @return void
	 */
	protected static function root($identifier, $controller, $root)
	{
		// First we need to strip "home" off of the controller name to create the
		// URI needed to match the controller's folder, which should match the
		// root URI we want to point to the index method.
        // 首先,我们需要从控制器名称中去除“home”以创建匹配控制器文件夹所需的 URI,
        // 该 URI 应该与我们想要指向 index 方法的根 URI 匹配。
		if ($controller !== 'home')
		{
			$home = dirname($controller);
		}
		else
		{
			$home = '';
		}

		// After we trim the "home" off of the controller name we'll build the
		// pattern needed to map to the controller and then register a route
		// to point the pattern to the controller's index method.
        // 在我们修剪掉控制器名称中的“home”之后,我们将构建映射到控制器所需的模式,
        // 然后注册一个路由以将该模式指向控制器的 index 方法。
		$pattern = trim($root.'/'.$home, '/') ?: '/';

		$attributes = array('uses' => "{$identifier}@index");

		static::register('*', $pattern, $attributes);
	}

	/**
	 * Find a route by the route's assigned name.
	 * 通过路由的指定名称查找路由。
	 * @param  string  $name
	 * @return array
	 */
	public static function find($name)
	{
		if (isset(static::$names[$name])) return static::$names[$name];

		// If no route names have been found at all, we will assume no reverse
		// routing has been done, and we will load the routes file for all of
		// the bundles that are installed for the application.
        // 如果根本没有找到路由名称,我们将假设没有进行反向路由,我们将为应用程序安装的所有包加载路由文件。
		if (count(static::$names) == 0)
		{
			foreach (Bundle::names() as $bundle)
			{
				Bundle::routes($bundle);
			}
		}

		// To find a named route, we will iterate through every route defined
		// for the application. We will cache the routes by name so we can
		// load them very quickly the next time.
        // 为了找到命名路由,我们将遍历为应用程序定义的每条路由。
        // 我们将按名称缓存路由,以便我们下次可以非常快速地加载它们。
		foreach (static::routes() as $method => $routes)
		{
			foreach ($routes as $key => $value)
			{
				if (isset($value['as']) and $value['as'] === $name)
				{
					return static::$names[$name] = array($key => $value);
				}
			}
		}
	}

	/**
	 * Find the route that uses the given action.
	 * 查找使用给定操作的路由。
	 * @param  string  $action
	 * @return array
	 */
	public static function uses($action)
	{
		// If the action has already been reverse routed before, we'll just
		// grab the previously found route to save time. They are cached
		// in a static array on the class.
        // 如果动作之前已经被反向路由,我们将只获取之前找到的路由以节省时间。 它们缓存在类的静态数组中。
		if (isset(static::$uses[$action]))
		{
			return static::$uses[$action];
		}

		Bundle::routes(Bundle::name($action));

		// To find the route, we'll simply spin through the routes looking
		// for a route with a "uses" key matching the action, and if we
		// find one we cache and return it.
        // 为了找到路线,我们将简单地遍历路线,寻找具有与操作匹配的“uses”键的路线,如果找到,我们将缓存并返回它。
		foreach (static::routes() as $method => $routes)
		{
			foreach ($routes as $key => $value)
			{
				if (isset($value['uses']) and $value['uses'] === $action)
				{
					return static::$uses[$action] = array($key => $value);
				}
			}
		}
	}

	/**
	 * Search the routes for the route matching a method and URI.
	 * 在路由中搜索匹配方法和 URI 的路由。
	 * @param  string   $method
	 * @param  string   $uri
	 * @return Route
	 */
	public static function route($method, $uri)
	{
		Bundle::start($bundle = Bundle::handles($uri));

		$routes = (array) static::method($method);

		// Of course literal route matches are the quickest to find, so we will
		// check for those first. If the destination key exists in the routes
		// array we can just return that route now.
        // 当然,文字路由匹配是最快找到的,所以我们将首先检查它们。 如果路由数组中存在目的地键,我们现在可以返回该路由。
		if (array_key_exists($uri, $routes))
		{
			$action = $routes[$uri];

			return new Route($method, $uri, $action);
		}

		// If we can't find a literal match we'll iterate through all of the
		// registered routes to find a matching route based on the route's
		// regular expressions and wildcards.
        // 如果我们找不到文字匹配,我们将遍历所有注册的路由,以根据路由的正则表达式和通配符找到匹配的路由。
		if ( ! is_null($route = static::match($method, $uri)))
		{
			return $route;
		}
	}

	/**
	 * Iterate through every route to find a matching route.
	 * 遍历每个路由以找到匹配的路由。
	 * @param  string  $method
	 * @param  string  $uri
	 * @return Route
	 */
	protected static function match($method, $uri)
	{
		foreach (static::method($method) as $route => $action)
		{
			// We only need to check routes with regular expression since all other
			// would have been able to be matched by the search for literal matches
			// we just did before we started searching.
            // 我们只需要使用正则表达式检查路由,因为在我们开始搜索之前,所有其他路由都可以通过搜索文字匹配来匹配。
			if (str_contains($route, '('))
			{
				$pattern = '#^'.static::wildcards($route).'$#';

				// If we get a match we'll return the route and slice off the first
				// parameter match, as preg_match sets the first array item to the
				// full-text match of the pattern.
                // 如果我们得到匹配,我们将返回路由并切掉第一个参数匹配,
                // 因为 preg_match 将第一个数组项设置为模式的全文匹配。
				if (preg_match($pattern, $uri, $parameters))
				{
					return new Route($method, $route, $action, array_slice($parameters, 1));
				}
			}
		}
	}

	/**
	 * Translate route URI wildcards into regular expressions.
	 * 将路由 URI 通配符转换为正则表达式。
	 * @param  string  $key
	 * @return string
	 */
	protected static function wildcards($key)
	{
		list($search, $replace) = array_divide(static::$optional);

		// For optional parameters, first translate the wildcards to their
		// regex equivalent, sans the ")?" ending. We'll add the endings
		// back on when we know the replacement count.
        // 对于可选参数,首先将通配符转换为其等效的正则表达式,没有“)?” 结尾。 当我们知道替换计数时,我们将重新添加结尾。
		$key = str_replace($search, $replace, $key, $count);

		if ($count > 0)
		{
			$key .= str_repeat(')?', $count);
		}

		return strtr($key, static::$patterns);
	}

	/**
	 * Get all of the registered routes, with fallbacks at the end.
	 * 获取所有已注册的路由,最后有回退。
	 * @return array
	 */
	public static function routes()
	{
		$routes = static::$routes;

		foreach (static::$methods as $method)
		{
			// It's possible that the routes array may not contain any routes for the
			// method, so we'll seed each request method with an empty array if it
			// doesn't already contain any routes.
            // 路由数组可能不包含该方法的任何路由,因此如果它尚未包含任何路由,我们将为每个请求方法设置一个空数组。
			if ( ! isset($routes[$method])) $routes[$method] = array();

			$fallback = array_get(static::$fallback, $method, array());

			// When building the array of routes, we'll merge in all of the fallback
			// routes for each request methdo individually. This allows us to avoid
			// collisions when merging the arrays together.
            // 在构建路由数组时,我们将单独合并每个请求方法的所有回退路由。 这允许我们在将数组合并在一起时避免冲突。
			$routes[$method] = array_merge($routes[$method], $fallback);
		}

		return $routes;
	}

	/**
	 * Grab all of the routes for a given request method.
	 * 获取给定请求方法的所有路由。
	 * @param  string  $method
	 * @return array
	 */
	public static function method($method)
	{
		$routes = array_get(static::$routes, $method, array());

		return array_merge($routes, array_get(static::$fallback, $method, array()));
	}

	/**
	 * Get all of the wildcard patterns
	 * 获取所有通配符模式
	 * @return array
	 */
	public static function patterns()
	{
		return array_merge(static::$patterns, static::$optional);
	}

	/**
	 * Get a string repeating a URI pattern any number of times.
	 * 获取重复 URI 模式任意次数的字符串。
	 * @param  string  $pattern
	 * @param  int     $times
	 * @return string
	 */
	protected static function repeat($pattern, $times)
	{
		return implode('/', array_fill(0, $times, $pattern));
	}

}

github地址: https://github.com/liu-shilong/laravel3-scr   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值