PHP/Laravel - 无法启动抽象类的扩展

Hak*_*Hak 3 php oop abstract-class interface laravel-4

我很擅长在PHP中使用抽象类和接口.

我正在尝试启动一个抽象类的扩展,但它不起作用.这可能是我遇到的Laravel特定问题.

情况就是这样:

  • 我有一个界面
  • 我有一个实现接口的抽象类
  • 我有'常规'类扩展抽象类
  • 我尝试实现这个类

这是界面:

<?php namespace Collection\Services\Validation;

interface SomeInterface {


    public function with(array $input);

    public function passes();

    public function errors();

}
Run Code Online (Sandbox Code Playgroud)

这是抽象类:

<?php namespace Collection\Services\Validation;

use Illuminate\Validation\Factory;

abstract class SomeClass implements SomeInterface {


    protected $validator;
    protected $data = array();
    protected $errors = array();
    protected $rules = array();


    public function __construct(Factory $validator)
    {
        $this->validator = $validator;
    }

    public function with(array $data)
    {
        $this->data = $data;

        return $this;
    }

    public function passes()
    {
        $validator = $this->validator->make($this->data, $this->rules);

        if( $validator->fails() )
        {
            $this->errors = $validator->messages();
            return false;
        }

        return true;
    }

    public function errors()
    {
        return $this->errors;
    }


}
Run Code Online (Sandbox Code Playgroud)

这是"常规"课程:

<?php namespace Collection\Services\Validation;


class SomeClassExtender extends SomeClass {


    public function sayBye()
    {
        return 'bye';
    }


}
Run Code Online (Sandbox Code Playgroud)

这是实施:

<?php

use Collection\Services\Validation\PageFormValidator;
use Collection\Services\Validation\SomeClassExtender;


class PagesController extends BaseController {


    protected $someClass;


    public function __construct(SomeClassExtender $class)
    {
        $this->someClass = $class;
    }
Run Code Online (Sandbox Code Playgroud)

然后我得到这个错误:

Illuminate \ Container \ BindingResolutionException
Target [Symfony\Component\Translation\TranslatorInterface] is not instantiable.
Run Code Online (Sandbox Code Playgroud)

如果我删除了Factory类的启动,则错误消失.Factory类也只是一个普通类.

我在这做错了什么?

Chr*_*ael 5

我看到你正在关注Chris Fidao的书.得到了和你一样的错误.

这是我的解决方案,将其放在global.php中

App::bind('Symfony\Component\Translation\TranslatorInterface', function($app) {
   return $app['translator']; 
});
Run Code Online (Sandbox Code Playgroud)

编辑:

我认为Factory的问题是你需要将翻译接口绑定到$ app ['translator'].这是我发现的......

如果查看Factory类,它需要转换器接口 - 快速查看API中的public __construct:

public function __construct(TranslatorInterface $translator, Container $container = null)
{
    $this->container = $container;
    $this->translator = $translator;
}
Run Code Online (Sandbox Code Playgroud)

然后,如果你查看ValidationServiceProvider中的公共函数register(),你会发现Laravel将TranslatorInterface绑定到$ app ['translator']:

$validator = new Factory($app['translator'], $app);
Run Code Online (Sandbox Code Playgroud)

然后看起来像是一个绑定$ app ['translator']的服务提供者,或者我们可以在global.php中绑定它.