Class :: getInstance的起源/解释?

med*_*iev 3 php oop class

我对古典继承相当新,因为我主要处理ECMAScript和Python,尽管我做了一些(颤抖)PHP.我知道它受Java和其他基于经典继承的语言的影响很大.

题:

我正在看一个框架中的几个类,并注意到'new'关键字没有被调用(至少直接)来创建实例,但是公共getInstance方法用于创建初始对象.

有人可以解释这背后的策略吗?我何时应该将它用于我自己的课程?

相关守则:

class FrontController {
    public static $_instance;

    public static function getInstance() {
        if ( !(self::$_instance instanceof self) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}

$front = FrontController::getInstance();
$front->route();
echo $front->getBody();
Run Code Online (Sandbox Code Playgroud)

完整代码:

class FrontController
{
    protected $_controller, $_action, $_params, $_body, $_url;

    public static $_instance;

    public static function getInstance()
    {
    if ( ! ( self::$_instance instanceof self) ) {
        self::$_instance = new self();
    }
    return self::$_instance;
    }

    private function __construct() {
    $this->uri = uri::getInstance();

    if ( $this->uri->fragment(0) ) {
        $this->_controller = $this->uri->fragment(0).'Controller';
    }
    else {
        $config = config::getInstance();
        $default = $config->config_values['application']['default_controller'].'Controller';
        $this->_controller = $default;
    }

    if ( $this->uri->fragment(1) ) {
        $this->_action = $this->_uri->fragment(1);
    } else {
        $this->_action = 'index';
    }
    }

    public function route() {
    $con = $this->getController();
    $rc = new ReflectionClass( $con );

    if ( $rc->implementsInterface( 'IController' ) ) {
        $controller = $rc->newInstance();

        if ( $rc->hasMethod( $this->getAction() ) ) {
        $method = $rc->getMethod( $this->getAction() );
        } else {
        $config = config::getInstance();
        $default = $config->config_values['application']['default_action'];
        $method = $rc->getMethod( $default );
        }
        $method->invoke( $controller );
    } else {
        throw new Exception('Interface iController must be implemented');
    }
    }

    public function getController() {
    if ( class_exists( $this->_controller ) ) {
        return $this->_controller;
    }
    else {
        $config = config::getInstance();
        $default = $config->config_values['application']['error_controller'].'Controller';
        return $default;
    }
    }

    public function getAction() {
    return $this->_action;
    }

    public function getBody() {
    return $this->_body;
    }

    public function setBody( $body ) {
    $this->_body = $body;
    }
}
Run Code Online (Sandbox Code Playgroud)

mal*_*avv 15

这很简单.看起来,很像Zend Framework的想法?
无论如何,这实现了Singleton设计模式.它禁止程序员创建多个控制器实例.那么,您是否可以从代码中的任何位置访问您的控制器,而不是创建一个新的FrontController或类似的东西,您只需要获得之前创建的One实例.

如果不存在任何实例,那么它正在创建一个其他实例,它只返回您之前创建的前端控制器.


希望这对你有所帮助!