自定义Laravel Validator类中的依赖注入,它扩展了LaravelValidator

时间:2013-10-08 13:23:02

标签: php laravel dependency-injection laravel-4

我需要在自定义Laravel Validator类中的一些验证方法中访问Db存储库,该类扩展了LaravelValidator。如何获得它?

我的类构造函数:

<?php namespace Pongo\Cms\Support\Validators;

use Illuminate\Validation\Validator as LaravelValidator;
use Pongo\Cms\Support\Repositories\PageRepositoryInterface as Page;
use Pongo\Cms\Support\Repositories\ElementRepositoryInterface as Element;

class PongoValidator extends LaravelValidator {

    /**
     * Class constructor
     * @param Page    $page 
     * @param Element $element
     */
     public function __construct($translator, $data, $rules, $messages, Page $page, Element $element)
     {
         $this->page = $page;
         $this->element = $element;
     }

     [...]

和我的Validator解析器(与Laravel文档一样):

<?php

/**
 * Instantiate CustomValidator class
 */
Validator::resolver(function($translator, $data, $rules, $messages)
{
    return new Pongo\Cms\Support\Validators\PongoValidator($translator, $data, $rules, $messages);
});

如何让它发挥作用? 感谢

1 个答案:

答案 0 :(得分:4)

好的......我找到了解决方案。

我的类构造函数:

<?php namespace Pongo\Cms\Support\Validators;

use Pongo\Cms\Support\Repositories\PageRepositoryInterface as Page;
use Pongo\Cms\Support\Repositories\ElementRepositoryInterface as Element;

use Illuminate\Validation\Validator as LaravelValidator;

use Config, Media, Str;

class PongoValidator extends LaravelValidator {

    private $page;

    private $element;

/**
 * Class constructor
 * @param Page    $page 
 * @param Element $element
 */
public function __construct($translator, $data, $rules, $messages, Page $page, Element $element)
{
    $this->translator = $translator;
    $this->data = $data;
    $this->rules = $this->explodeRules($rules);
    $this->messages = $messages;

    $this->page = $page;
    $this->element = $element;
}

[...]

和我的Validator解析器(IoC救援!!):

<?php

use Pongo\Cms\Support\Validators\PongoValidator;

/**
 * Instantiate CustomValidator class
 */
Validator::resolver(function($translator, $data, $rules, $messages)
{
    $page = App::make('Pongo\Cms\Support\Repositories\PageRepositoryInterface');

    $element = App::make('Pongo\Cms\Support\Repositories\ElementRepositoryInterface'));

    return new PongoValidator($translator, $data, $rules, $messages, $page, $element);
});

希望它可以帮助其他人...... 再见