【问题标题】:PHP Classes - Better alternative to $this->base->class->methodPHP 类 - 更好的替代 $this->base->class->method
【发布时间】:2012-01-28 15:00:12
【问题描述】:

目前,我有一个主类 Base 加载所有其他控制器和模型,然后由 Base 加载的每个类都有类似的结构:

class SomeClass {

    private $base;

    function __construct(&$base) {
        $this->base = $base;
    }

    function SomeMethod() { }

}

然后另一个类将不得不使用:

class AnotherClass {

    private $base;

    function __construct(&$base) {
        $this->base = $base;

        $this->base->SomeClass->SomeMethod();
    }

}

有没有更好的方法来访问这些其他类?

【问题讨论】:

  • 你看过类 SomeClass extends BaseClass 吗?
  • 它们不扩展 BaseClass 的功能。它们由它加载,然后由 BaseClass 出于某些目的调用。例如。 BaseClass 可能会调用 DatabaseClass 和 AuthenticationClass,然后是一个使用 AuthenticationClass 和 DatabaseClass 的控件 SomeController。
  • 对不起,看来我没有正确理解你原来的问题,请忽略我之前的评论。

标签: php oop base-class


【解决方案1】:

也许 someMethod() 可能是静态的:

class SomeClass {

    private $base;

    function __construct(&$base) {
        $this->base = $base;
    }

    public static function SomeMethod() { }

}

然后就是:

class AnotherClass {

    private $base;

    function __construct(&$base) {
        $this->base = $base;

        SomeClass::SomeMethod();
    }

}

【讨论】:

  • 感谢您的建议。这不适用于我必须使用这些类但会在几种情况下使用的所有情况。
【解决方案2】:

听起来BaseFront Controller pattern 的实现。前端控制器是Mediator 的一个特例,它完全按照您的方式工作。它本质上允许 SomeClassAnotherClass 以更少的依赖项单独开发和维护。

但是,与其直接从Base 类访问这些类,不如让SomeClassAnotherClassBase 类注册自己,并公开其他对象调用的getter 方法:

class Base {
    protected $_authenticator;

    public function setAuthenticator(Authenticator $auth) {
        $this->_authenticator = $auth;
    }

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

class Authenticator {
    protected $_base;

    public function __construct(Base $base) {
        $this->_base = $base;
        $this->_base->setAuthenticator($this);
    }
}

【讨论】:

  • 感谢您对此的说明。我将尝试在我的项目中实现这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
  • 2017-01-29
  • 2016-12-08
相关资源
最近更新 更多