dpxyfa4718 2016-06-24 18:32
浏览 24

DI软件构造函数或获取/设置 - 最佳实践

I am currently creating my own dependency injection software but am finding that it seems a lot like do this, do that to get this (if that makes sense).

class FactoryDatabase extends PDO
{
    public function __construct(
        $dsn,$user,$pass
    ) {
        parent::__construct($dsn,$user,$pass);
    }
}

class DependencyInjectionContainer
{
    protected $Con;
    public function __construct(
        $db_factory
    ) {
        $this->Con = $db_factory;
    }
}

$container = new DependencyInjectionContainer(new FactoryDatabase(....

I am not fully understanding where to use constructors and where to use set/get methods since there is too many possibilities of achieving this.

For better practice, I'd like to understand if its better to use constructors or methods like these:

protected $Callbacks;
public function set(
    $foo,$bar
) {
    if(!empty($this->Callbacks[$foo]))    {
        $this->Callbacks[$foo] = $bar;
    }
}

$container = new DependencyInjectionContainer();
$container->set('db', new FactoryDatabase(......

But now I get a problem where creating a get method will allow direct access to the database object rather than only through the DI container object.

I thought of a come around using both constructors and get/set methods:

public function __construct(
    FactoryDatabase $db
) {
    $this->Con = $db;
}

public function getFunction(
    $foo
) {
    return $this->Callbacks[$foo]($this);
}

public function getValue(
    $foo
) {
    return $this->Callbacks[$foo];
}

This allows me to use the Callbacks as values or anonymous functions but also access the methods inside the function, something like:

$container->set('db_select_members', function($obj){
    return $obj->....
});

Is this best practice? Or how can I improve this DI software to allow full dynamics keeping Objects unclear to other Objects.

The only issue again is now there is direct access through the anonymous function to objects which could of just been accessed like:

$container->Object

So it seems a waste of time?

  • 写回答

1条回答 默认 最新

  • dongshuofu0039 2016-06-24 19:13
    关注

    In most ceses best is to use tested and ready to use libs like symfony di (http://symfony.com/doc/current/components/dependency_injection/introduction.html)

    If you realy need to write your own best use is to create class with get-ers like

    https://justpaste.it/vlpm

    etc

    and use only container as replacement for factories

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题