本文介绍了如何使PHP库松散耦合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的框架"中有一些库,例如路由,配置,记录器,...我希望它们彼此独立,就像一些众所周知的PHP框架使它们独立一样.

I have some libraries in my 'framework' like routing, config, logger,... I want them to be independent of each other, like some of well known PHP frameworks make them.

我了解松耦合的所有原理,但是我不知道如何同时遵循松耦合和DRY原理.如果我将路由库用作配置和记录器,那么我就不重复了,但是如果我想单独使用路由器,它将无法正常工作.同样,如果我将日志记录和配置代码写入路由库,我会重复自己.

I understand all the principles of loose coupling, but I have no clue how to follow both loose coupling and DRY principles. If I make routing library that config and logger, then I don't repeat myself, but if I want to use router on its own it won't work. Similarly if I write logging and config code into my routing library, I would repeat myself.

推荐答案

松耦合通常意味着您的组件不期望一个具体的实例,而只是一个具有兼容接口的实例.

Loose coupling normally means that your components do not expect a concrete instance but just one instance that has a compatible interface.

然后可以将每个协作者替换为相同类型的另一个协作者.该代码不再依赖于其中之一的具体实现.

Each collaborator can be replaced then with a different one of the same type. The code is not dependent on a concrete implementation of one of those any longer.

所以:

  • 请勿使用:

  • Do not use:

  • 全局(静态)函数

  • global (static) functions

Foo:bar();

  • 基于类的编程(传递类名)

  • class based programming (passing a classname around)

    stream_wrapper_register("var", "VariableStream");
    

  • 全局常量

  • global constants

    if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');
    

  • 但是:

    • 使用对象

    • Use objects

    $foo->bar();
    

  • 针对接口的程序

  • Program against interfaces

    public function __construct(LoggerInterface $logger) {
    

  • 带有模拟的单元测试

  • Unit-test with mocks

    $logger = $this->getMock('LoggerInterface', array('log'));
    

  • 另请参见:

    这篇关于如何使PHP库松散耦合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-04 21:06