Roh*_*han 0 php laravel laravel-5 laravel-ioc
所以我有一个BaseValuation抽象类及其实现示例FooValuation和BarValuation.
我想根据使用输入来实例化Foo或实现。Bar所以我自己创建了一个简单的类,Valuation它的作用是:
<?php
namespace App\Valuation;
class Valuation
{
public $class;
public function __construct($id, $type = 'basic')
{
$class = 'App\Valuation\Models\\' . ucfirst($type) . 'Valuation';
$this->class = new $class($id);
}
public function make()
{
return $this->class;
}
}
Run Code Online (Sandbox Code Playgroud)
使用这个我可以简单地做到这一点(new App\Valuation\Valuation($id, $type))->make(),我将根据用户的要求获得所需的实现。
但我知道 laravel 的容器很强大,必须允许我以某种方式做到这一点,但我不明白这是如何完成的。有人有什么想法吗?
您可以将类绑定到任何字符串,通常这是在服务提供者中完成的。
$this->app->bind('string', SomethingValuation::class);
Run Code Online (Sandbox Code Playgroud)
然后你可以用 实例化它App::make('string')。
我认为当您将单个实现(具体)绑定到接口(抽象)而不是绑定多个类时,这更有价值。
您也可以只允许 Laravel 通过调用来实例化该类App::make(\Full\Path::class)。
两者都允许您将模拟注入到具有相同名称的容器中以进行测试。
| 归档时间: |
|
| 查看次数: |
2164 次 |
| 最近记录: |