Safe alternatives to PHP Globals (Good Coding Practices)

后端 未结 6 1223
渐次进展
渐次进展 2020-12-03 04:03

For years I have used global $var,$var2,...,$varn for methods in my application. I\'ve used them for two main implementations:

Getting an already set cl

6条回答
  •  天命终不由人
    2020-12-03 04:28

    One option that some people may frown upon is to create a singleton object responsible for holding the application state. When you want to access some shared "global" object you could make a call like: State::get()->db->query(); or $db = State::get()->db;.

    I see this method as a reasonable approach as it saves having to pass around a bunch of objects all over the place.

    EDIT:

    Using this approach can help simplify the organization and readability of your application. For example, your state class could call the proper methods to initialize your database object and decouple its initialization from your showPage function.

    class State {
        private static $instance;
        private $_db;
    
        public function getDB() {
            if(!isset($this->_db)){ 
                // or call your database initialization code or set this in some sort of
                // initialization method for your whole application
                $this->_db = new Database();
            }
            return $this->_db;
        }
    
        public function getOutput() {
            // do your output stuff here similar to the db
        }
    
        private function __construct() { }
    
        public static function get() {
            if (!isset(self::$instance)) {
                $className = __CLASS__;
                self::$instance = new State;
            }
            return self::$instance;
        }
    
        public function __clone() {
            trigger_error('Clone is not allowed.', E_USER_ERROR);
        }
    
        public function __wakeup() {
            trigger_error('Unserializing is not allowed.', E_USER_ERROR);
        }
    }
    

    and your show page function could be something like this:

    function showPage(){
         $output = State::get()->getOutput();
         $output['header']['title'] = State::get()->getDB()->getConfig( 'siteTitle' );
         require( 'myHTMLPage.html' );
         exit();
    }
    

    An alternative to using a singleton object is to pass the state object to your various functions, this allows you to have alternative "states" if your application gets complicated and you will only need to pass around a single state object.

    function showPage($state){
         $output = $state->getOutput();
         $output['header']['title'] = $state->getDB()->getConfig( 'siteTitle' );
         require( 'myHTMLPage.html' );
         exit();
    }
    
    $state = new State; // you'll have to remove all the singleton code in my example.
    showPage($state);
    

提交回复
热议问题