Laravel路由器命名空间方法



在Laravel文档路由中有一个命名空间方法。

Route::namespace

我试图探索它到底做了什么,但在Laravel源代码中找不到它的定义。它在哪里?

它与代码无关,只是对路由进行分组。喜欢这个:

源代码在这里:https://github.com/laravel/framework/blob/b73691ac7b309cd2c4fb29b32d3eed76fecca58b/src/Illuminate/Routing/RouteGroup.php#L40,它只是在当前命名空间的末尾添加命名空间。

例如,您有一个控制器组,例如"产品",

App/
Http/
Controllers/
Products/
Stocks.php 
Prices.php
Sizes.php 

您需要像这样修改它们的命名空间以满足 PSR-4 要求,以启用控制器的自动加载:

namespace AppHttpControllersProducts;            
class Stocks {
function index(){
}
}

然后,如果要访问这些控制器的方法,则可能需要使用Route::namespace()对它们进行分组:

Route::namespace("Products")->group(function(){
Route::get("stocks", "Stocks@index");
});

这将在AppHttpControllersProducts命名空间而不是AppHttpControllers命名空间中搜索Stocks类。 并调用index方法。

请注意,您可以运行composer dumpautoload让框架使用 PSR-4 命名空间重新生成自动加载.php以使这些内容有效。


后期编辑:

framework/src/Illuminate/Routing/Router.php定义了Route类,该类将Route::namespace方法重定向到RouterRegistrar以下行的类:

/**
* Dynamically handle calls into the router instance.
*
* @param  string  $method
* @param  array  $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
if ($method == 'middleware') {
return (new RouteRegistrar($this))->attribute($method, is_array($parameters[0]) ? $parameters[0] : $parameters);
}
return (new RouteRegistrar($this))->attribute($method, $parameters[0]);
}

在最后一行。在这种方法中,

/**
* The attributes that can be set through this class.
*
* @var array
*/
protected $allowedAttributes = [
'as', 'domain', 'middleware', 'name', 'namespace', 'prefix',
];
/**
* Set the value for a given attribute.
*
* @param  string  $key
* @param  mixed  $value
* @return $this
*
* @throws InvalidArgumentException
*/
public function attribute($key, $value)
{
if (! in_array($key, $this->allowedAttributes)) {
throw new InvalidArgumentException("Attribute [{$key}] does not exist.");
}
$this->attributes[Arr::get($this->aliases, $key, $key)] = $value;
return $this;
}

正在设置namespace属性,以便在->group()方法中使用。

最新更新