Laravel - 如何在验证规则构造中自动注入(inject)?

标签 laravel laravel-5

我无法通过 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/

相关文章:

php - 调用未定义函数 App\Http\Controllers\[ 函数名称 ]

php - 使用了无效的操作数类型 : array_uintersect expects array(s)

php - 如何在 Laravel 中扩展外观?

php - 无法在 laravel 应用程序中保存资源传递给 Illuminate\Database\Grammar::parameterize() 的参数 1 必须是数组类型,给定为 null

jquery - 通过ajax从Laravel 4中的数据库将数据加载到 View 中

mysql - 如何返回商店评论大于或等于输入的所有商品 - Laravel 5.2

laravel - 如何检查laravel中是否使用了分页

javascript - 选定的下拉框值不会更改 laravel 5 中的另一个字段值

Laravel Sail 作为生产设置

javascript - 在没有 Controller 的情况下将所有 Angular 值相加