我无法通过 Laravel 注入(inject)这些变量:
//...class AllowedUsername implements Rule...
public function __construct(Router $router, Filesystem $files, Repository $config)
{
$this->router = $router;
$this->files = $files;
$this->config = $config;
}
我收到错误:
Type error: Too few arguments to function ... 0 passed in.
为什么 Laravel 不自动执行此操作?
$request->validate([
'username' => ['required', new AllowedUsername],
]);
最佳答案
为了利用 Laravel 的注入(inject)魔法,您需要使用 Laravel 的 API,它本质上是:
-
resolve($class)
这是app($class)
的包装 -
app($class, $params = [])
这是包装:
Note: I've changed
$abstract
for$class
if (is_null($class)) {
return Container::getInstance();
}
return Container::getInstance()->make($class, $parameters);
您想要从容器中解析的类(如代码示例中所示):
public function __construct(Router $router, Filesystem $files, Repository $config)
之所以能够被解析,只是因为 Laravel 维护者已经为 Router::class
定义了绑定(bind)。 , Filesystem:class
(例如: FilesystemServiceProvider )。
Repository::class
似乎是简单类,在“更新”时不需要参数(或需要容器已经知道如何解析的参数) - 因此 Laravel 可以毫无问题地解决它。
There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.
这就是为什么 resolve(AllowedUser::class)
或resolve(Router::class)
...工作。
为了让 Laravel 知道在“更新”期间应该发送哪些构造函数的参数,您可以使用documentation中提到的绑定(bind)。 .
关于Laravel - 如何在验证规则构造中自动注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49222500/