0

我有一个非常大的脚本。它有一个数据库类、一个基类、一个用户认证类、一个经销商认证类、paypal ipn 类、一个下载类和一个插件类

Base 类扩展数据库类,如下所示:

class Base extends database
{
    var $userid;
    var $root;
    var $config

    function Base($username, $password, $host, $database)
    {
        // Init DB
        $this -> database($hostname, $database, $username, $password);
        $this -> config = $this -> fetch(...);
        // and the code goes on
    }
    function anyFunction()
    {
        $this -> Downloads -> dloadFunction();
    }
}
class users extends Base
{
    var $userData;

    function users()
    {
        // initialize user, check if he is logged in, if he has cookies, load the user vars in $this -> userData
    }
    function userFunction1()
    {
        $this -> anyFunction();
    }
}
class resellers extends Base
{
    var $resellerData;

    function resellers()
    {
        // initialize resellers, check if he is logged in, if he has cookies, load the user vars in $this -> resellerData
    }
}
class IPN extends Base
{

}
class Downloads extends Base
{
    function dloadFunction()
    {

    }
}
class Plugins extends Downloads
{

}
?>

我这样称呼我的代码:

<?php
    $Base = new Base($user, $pass, $host, $db);
    $user = new user();
    $Base -> user = $user;
    $reseller = new reseller();
    $Base -> reseller = $reseller;
    $downloads = new Downloads();
    $downloads -> Plugins = new Plugins();
    $Base -> Downloads = $downloads;

    $Base -> users -> updateEmail();
    // and the code goes on..
?>

我认为结构非常糟糕。这就是为什么我要实现单例方法。我怎样才能做到这一点?

请帮忙。

4

1 回答 1

1

PHP 中的单例模式实现示例(自 5.3 起):

/**
 * Singleton pattern implementation
 */
abstract class Singleton {

    /**
     * Collection of instances
     * @var array
     */
    private static $_aInstance = array();

    /**
     * Private constructor
     */
    private function __construct(){}

    /**
     * Get instance of class
     */
    public static function getInstance() {

    // Get name of current class
    $sClassName = get_called_class();

    // Create new instance if necessary
    if( !isset( self::$_aInstance[ $sClassName ] ) )
        self::$_aInstance[ $sClassName ] = new $sClassName();
        $oInstance = self::$_aInstance[ $sClassName ];

        return $oInstance;
    }

    /**
     * Private final clone method
     */
    final private function __clone(){}
}

使用示例:

class Example extends Singleton {}
$oExample1 = Example::getInstance();
$oExample2 = Example::getInstance();
echo ( is_a( $oExample1, 'Example' ) && $oExample1 === $oExample2)
    ? 'Same' : 'Different', "\n"; 
于 2010-09-08T01:28:53.590 回答