我对在 PHP 中使用抽象类和接口(interface)还很陌生。
我正在尝试启动一个抽象类的扩展,但它不起作用。这可能是我遇到的 Laravel 特定问题。
是这样的:
- 我有一个界面
- 我有一个实现接口(interface)的抽象类
- 我有扩展抽象类的“常规”类
- 我尝试实现这个类
这是界面:
<?php namespace Collection\Services\Validation;
interface SomeInterface {
public function with(array $input);
public function passes();
public function errors();
}
这是抽象类:
<?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;
}
}
这是“常规”类:
<?php namespace Collection\Services\Validation;
class SomeClassExtender extends SomeClass {
public function sayBye()
{
return 'bye';
}
}
这是实现:
<?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;
}
然后我得到这个错误:
Illuminate \ Container \ BindingResolutionException
Target [Symfony\Component\Translation\TranslatorInterface] is not instantiable.
如果我删除工厂类的启动,错误就消失了。 Factory 类也只是一个普通类。
我做错了什么?
最佳答案
我看到您正在关注 Chris Fidao 的书。遇到了和你一样的错误。
这是我的解决方案,将它放在 global.php 中
App::bind('Symfony\Component\Translation\TranslatorInterface', function($app) {
return $app['translator'];
});
编辑:
我认为 Factory 的问题在于您需要将翻译器接口(interface)绑定(bind)到 $app['translator']。这是我发现的……
如果您查看 Factory 类,它需要翻译器接口(interface)——快速查看它在 API 中的公共(public) __construct:
public function __construct(TranslatorInterface $translator, Container $container = null)
{
$this->container = $container;
$this->translator = $translator;
}
然后如果你查看 ValidationServiceProvider 中的公共(public)函数 register(),你会发现 Laravel 将 TranslatorInterface 绑定(bind)到 $app['translator']:
$validator = new Factory($app['translator'], $app);
那么似乎需要一个服务提供者来绑定(bind) $app['translator'],或者我们可以在 global.php 中绑定(bind)它。
关于PHP/Laravel - 无法启动抽象类的扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20142020/