如何在laravel之外正确实例化Iluminate类

时间:2015-07-12 10:10:58

标签: validation laravel eloquent

我有口才在Laravel外工作没有问题。现在我试图通过以下方式使用Validation类:

<?php

namespace User;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Validator;

class User extends Model {

    private $rules = array(
        'firstName' => 'required|min:2|max:50',
        'lastName'  => 'required|min:2|max:50',
    );

    public function validate($data)
    {
        $v = Validator::make($data, $this->rules);
        return $v->passes();
    }

}

执行该代码会给我一个错误:

 Call to undefined method Illuminate\Validation\Validator::make()

这是正确的,因为方法 make 不在类Validator上,而是在他的工厂中: enter image description here

如何正确实例化Validation lib以使其正常工作?

是的,这是我的composer.json:

{
    "require": {
        "slim/slim": "^2.6",
        "illuminate/database": "^5.1",
        "illuminate/validation": "^5.1"
    },
    "autoload": {
        "classmap": [
            "app/model"
        ]
    }

}

2 个答案:

答案 0 :(得分:5)

要让验证包在Laravel之外工作,您还需要翻译包。

首先创建一个翻译实例,然后用它来创建一个验证工厂。

工作示例

<?php

/*
Required composer packages:
    illuminate/validation
    illuminate/translation
*/

/*
Translation language files directory is the same as with Laravel
    ./lang/en/validation.php
*/

require_once 'vendor/autoload.php';

// You need to specify where the translation files is
$test_translation_path = __DIR__.'/lang';
$test_translation_locale = 'en';

// Set up data for the validator
$test_input_data = ['field' => 'value'];
$test_input_rules = ['field' => 'required'];

$translation_file_loader = new Illuminate\Translation\FileLoader(new Illuminate\Filesystem\Filesystem, $test_translation_path);

$translator = new Illuminate\Translation\Translator($translation_file_loader, $test_translation_locale);

$validation_factory = new Illuminate\Validation\Factory($translator);

$validator = $validation_factory->make($test_input_data, $test_input_rules);

if ($validator->fails()) {
    die('Validation failed');
}

die('Validation passed!');

答案 1 :(得分:4)

您的方法存在一些问题:

  • 您正在尝试通过调用Validator方法创建新的Illuminate\Validation\Validator::make实例,但您指出make()方法存在Illuminate\Validation\Factory方法这是一个完全不同的类,所以你得到的错误是合理的。

  • 您试图静态调用make()方法::实际上并未将其定义为此类。

  • 您正在尝试使用与Laravel应用程序环境中相同的Validator,因为您错过了Laravel用于实现如此简单实例化的Laravel Facades和Service Providers基础结构,因此无法使用。验证者。

如果您要查看registerValidationFactory()类中的Illuminate\Validation\ValidationServiceProvider方法,您将了解验证程序实例的创建方式。因此,基于此,您可以执行以下操作:

namespace User;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Validation\Factory as ValidatorFactory;
use Symfony\Component\Translation\Translator;

class User extends Model {

    private $rules = array(
        'firstName' => 'required|min:2|max:50',
        'lastName'  => 'required|min:2|max:50',
    );

    public function validate($data)
    {
        $factory = new ValidatorFactory(new Translator('en'));
        $v = $factory->make($data, $rules);

        return $v->passes();
    }

}