Laravel-如何在验证规则构造中自动注入? [英] Laravel - How do I inject automatically in Validation Rule Construct?

查看:179
本文介绍了Laravel-如何在验证规则构造中自动注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过Laravel注入这些变量:

I'm not able to inject these variables through Laravel:

//...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为什么不自动执行该操作?

Why is Laravel not doing it automatically?

$request->validate([
            'username' => ['required', new AllowedUsername],           
        ]);

推荐答案

为了利用Laravel的注入魔术,您需要使用Laravel的API,该API本质上是:

In order to leverage Laravel's injection magic you need to use Laravel's API which essentially is:

  • resolve($class),它包装在app($class)
  • 周围
  • app($class, $params = []),这是包装:
  • resolve($class) which is wrapper around app($class)
  • app($class, $params = []) which is wrapper around:

注意:我已将$abstract更改为$class

Note: I've changed $abstract for $class

if (is_null($class)) {
    return Container::getInstance();
}

return Container::getInstance()->make($class, $parameters);


要在容器外解析的类(如代码示例所示):


Classes that you want to resolve out of container (as seen in your code sample):

public function __construct(Router $router, Filesystem $files, Repository $config)

之所以能解决,是因为Laravel维护者已经为Router::classFilesystem:class定义了绑定(示例:

can be resolved only because Laravel maintainers already defined binding for Router::class, Filesystem:class (example: FilesystemServiceProvider).

Repository::class似乎是简单类,在更新"时不需要参数(或要求容器已经知道如何解析的参数),因此Laravel可以毫无问题地解决它. /p>

Repository::class seems to be simple class that does not require parameters (or require parameters that container already knows how to resolve) while "newing up" - thus Laravel can resolve it without problem.

如果类不依赖于任何接口,则无需将类绑定到容器中.无需指示容器如何构建这些对象,因为它可以使用反射自动解析这些对象.

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) ...起作用的原因.

Thats why resolve(AllowedUser::class) or resolve(Router::class)... work.

为了让Laravel知道在更新"期间应发送哪些构造函数的参数,请使用

In order to let Laravel know what constructor's parameters should be sent during "newing up" you use bindings mentioned in documentation.

这篇关于Laravel-如何在验证规则构造中自动注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆