Jump to content

I have a simple registry class working.. just need to tweak it...


cgm225

Recommended Posts

I have the following simple registry class working, but I wanted to know where I should be including all my registry->set() methods that are used to put variables/objects in the registry.  Should I have a settings file?  If so, is there a way to include those variables in a simple way in a .ini file without a redundant $registry->set statement each line?  Could you provide me with some example code?

 

Thank you all in advance!

 

My registry class

class Registry {
    
    //Declaring variables
    private $store = array();
    static private $thisInstance = null;

    //Class constructor
    public function __construct() {}
    
    static public function getInstance() {
        if(self::$thisInstance == null) {
            self::$thisInstance = new Registry();
        }
        return self::$thisInstance;
    }
    
    //Setting registry variable
    public function set($label, $object) {
        if(!isset($this->store[$label])) {
            $this->store[$label] = $object;
        }
    }
   
    //Getting registry variable    
    public function get($label) {
        if(isset($this->store[$label])) {
            return $this->store[$label];
        }
        return false;
    }
}

 

Example of current instantiation (which I do in my index.php5 file)

//Instantiating registry & setting variables/objects
$registry = new Registry();
$registry->set('pageDir', MVC_ROOT);              //Registering page directory
$registry->set('mysqli', $mysqli);                //Registering MySQLi object

well...if you want to use an INI file, you can add a method to your class which utilizes http://us3.php.net/parse_ini_file to set the variables...

 

but i usually just setup a config.inc file that gets included on every page, and do the individual $registry->set(); calls on each line

 

another thought...you can have another method called setArray() and allow an array of key/value pairs to be passed

How does this look?  Does my file naming look ok?  And am I including everything in good locations?  Do you have any other feedback?

 

Thanks again!

 

My index.php5 (where I instantiate the registry):

<?php

//Initializing session
session_start();

//General includes
require_once 'configurations.php5';               //General configurations
require_once MVC_ROOT . '/MysqliSetConnect.php5'; //MySQLi settings & connection
require_once MVC_ROOT . '/Registry.php5';         //Registry class and items
require_once MVC_ROOT . '/Authentication.php5';   //User authentication

//Instantiating registry
$registry = new Registry($registryItems);

//Including MVC classes and instatiating front controller
require_once MVC_ROOT . '/ModelViewController.php5';
$controller = FrontController::getInstance();
$controller->setRegistry($registry);              
$controller->dispatch(false);

//Closing MySQLi object created in MysqliSetConnect.php5 (included above)
$mysqli->close();

?>

 

My Registry.php5

<?php

//Registry class
class Registry {
    
    //Declaring variables
    private $store;

    //Class constructor
    public function __construct($store = array()) {
        $this->store = $store;
    }
    
    //Sets registry variable
    public function set($label, $object) {
        if(!isset($this->store[$label])) {
            $this->store[$label] = $object;
        }
    }
   
    //Gets registry variable    
    public function get($label) {
        if(isset($this->store[$label])) {
            return $this->store[$label];
        }
        return false;
    }
}

/* Requiring file with a $registryItems array for use in the Registry class
* constructor.  This is NOT required for the registry class to work properly.
*/
require_once MVC_ROOT . '/RegistryItems.php5';

?>

 

My RegistryItems.php5

<?php

$registryItems = array();

$registryItems['pageDir'] = MVC_ROOT; //**Required by MVC classes
$registryItems['mysqli']  = $mysqli;

?>

 

My ModelViewController.php5

<?php

class FrontController extends ActionController {

    //Declaring variable(s)
    private static $instance;
    protected $controller;

    //Class construct method
    public function __construct() {}

    //Starting new instance of this class with a singleton pattern
    public static function getInstance() {
        if(!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function dispatch($throwExceptions = false) {
        /*  
            Checking for the GET variables $module and $action, and, if present,
            will strip them down with a regular expression function with a white
            list of allowed characters, removing anything that is not a letter,
            number, underscore or hyphen.
        */
        $regex  = '/[^-_A-z0-9]++/';
        $module = isset($_GET['module']) ? preg_replace($regex, '', $_GET['module']) : 'home';
        $action = isset($_GET['action']) ? preg_replace($regex, '', $_GET['action']) : 'frontpage';

        /*
            Generating Actions class filename (example: HomeActions) and path to
            that class (example: home/HomeActions.php5), checking if $file is a
            valid file, and then, if so, requiring that file.
        */
        $class = ucfirst($module) . 'Actions';
        $file  = $this->pageDir . '/' . $module . '/' . $class . '.php5';

        if (!is_file($file)) {
            throw new FrontControllerException('Page not found!');
        }

        require_once $file;

        /*  
            Creating a new instance of the Actions class (example: $controller
            = new HomeActions(), and passing page directory variable to the
            ActionController class.
        */
        $controller = new $class();
        $controller->setRegistry($this->registry);

        try {
            //Using the setModule method in the ActionController class
            $controller->setModule($module);

            /*
                The ActionController dispatchAction method checks if the method
                exists, then runs the displayView function in the
                ActionController class.
            */    
            $controller->dispatchAction($action);
        }
        catch(Exception $error) {

            /*
                An exception has occurred, and will be displayed if
                $throwExceptions is set to true.
            */
            if($throwExceptions) {
                echo $error->errorMessage($error); //Full exception echoed
            } else {
                echo $error->errorMessage(null); //Simple error messaged echoed
            }
        }
    }
}

abstract class ActionController {

    //Declaring variable(s)
    protected $registry;
    protected $module;
    protected $viewData = array();
    
    //Class construct method
    public function __construct(){
               
        /* Setting variables for objects external to the MVC that are used in
         * multiple modules.  These objects add NO functionality to the actual
         * MVC classes, but are used by multiple modules.  THIS WILL BE GOING
         * THE REGISTRY.. NOT FINISHED!!
         */
        $this->auth = MysqliAuthentication::getInstance(); //User authentication
    }
    
    public function setRegistry($registry) {
        
        //Sets the registry object
        $this->registry = $registry;
        
        /* Once the registry is loaded, the MVC root directory path is set from
         * the registry.
         */
        $this->setPageDir();
    }
    
    //Sets the MVC root directory from the value stored in the registry
    public function setPageDir() {
        $this->pageDir = $this->registry->get('pageDir');
    }

    //Sets the module
    public function setModule($module) {
        $this->module = $module;
    }

    //Gets the module
    public function getModule() {
        return $this->module;
    }

    //Placing a value in the $viewData array at the key position
    public function setVar($key, $value) {
        $this->viewData[$key] = $value;
    }

    //Returns a value from the $viewData array located at the key position
    public function getVar($key) {
        if (array_key_exists($key, $this->viewData)) {
            return $this->viewData[$key];
        }
    }

    //Gets the viewData array
    public function getViewData($viewData) {
        $this->viewData = $viewData;
    }

    /*
        Checking for actionMethod in the Actions class (example: doFrontpage()
        within home/HomeActions.php5) with the method_exists function and, if
        present, the actionMethod and displayView functions are executed.
    */  
    public function dispatchAction($action) {
        $actionMethod = 'do' . ucfirst($action);
        if (!method_exists($this, $actionMethod)) {
            throw new FrontControllerException('Page not found!');
        }
        $this->$actionMethod();
        $this->displayView($action);
    }

    public function displayView($action) {
        if (!is_file($this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php5')) {
            throw new FrontControllerException('Page not found!');
        }

        //Setting $this->actionView to the path of the action View file
        $this->actionView = $this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php5';

        /*
            Creating a new instance of the View class and passing the $pageDir,
            $viewData, and actionView variables
        */  
        $view = new View();
        $view->setRegistry($this->registry);
        $view->getViewData($this->viewData);
        $view->setVar('actionView',$this->actionView);
        $view->render();
    }
}

class View extends ActionController {

    public function render() {

        //Including default template settings
        require_once $this->pageDir . '/defaultTplSettings.php5';

        /*
            Merging the default template variables with variables provided in
            the $this->viewData array, taken from the Actions class, giving
            priority to those provided by the action class, then extracting the
            array with the extract() function, which creates a variable for
            every array value, and the name of the value (the variable name) is
            the key's value.
        */
        $templateSettings = array_merge($defaultTemplateSettings, $this->viewData);
        extract($templateSettings, EXTR_OVERWRITE);

        //Including template file within which the action View file is included
        require_once $this->pageDir . '/default.tpl';
    }
}

class FrontControllerException extends Exception {
    public function errorMessage($error) {
        
        /*
            If and throwExceptions is true, then the full exception will be
            returned.
        */
        $errorMessage = isset($error) ? $error : $this->getMessage();
        return $errorMessage;
    }
}

?>

Couple other things you may want to look into:

 

Overloading

http://us.php.net/manual/en/language.oop5.overloading.php

This would be useful for the Registry class. Might be unnecessary, but worth a look through.

 

Autoloading

http://us.php.net/manual/en/language.oop5.autoload.php

You can use this to automatically load your classes on the fly. This way you don't need to put the require_once() statements in each time.

 

INIT

I usually have an init.inc file, that sets up all my config/databases/controllers/etc, then on each page, I just include that init.inc file.

Thank you for all your help.  I will look into all those things.  Also, a follow-up question.. I want to make sure I am keeping my module logic separate from my MVC logic.  However, my user authentication class/module is used by almost all my other modules/apps, and so I have been including it in my MVC class as shown below (maybe use control-F with "user authentication" to find the line faster).

 

Is this ok to do, or is there somewhere better I should be setting this variable? 

 

 

<?php

class FrontController extends ActionController {

    //Declaring variable(s)
    private static $instance;
    protected $controller;

    //Class construct method
    public function __construct() {}

    //Starting new instance of this class with a singleton pattern
    public static function getInstance() {
        if(!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function dispatch($throwExceptions = false) {
        /*  
            Checking for the GET variables $module and $action, and, if present,
            will strip them down with a regular expression function with a white
            list of allowed characters, removing anything that is not a letter,
            number, underscore or hyphen.
        */
        $regex  = '/[^-_A-z0-9]++/';
        $module = isset($_GET['module']) ? preg_replace($regex, '', $_GET['module']) : 'home';
        $action = isset($_GET['action']) ? preg_replace($regex, '', $_GET['action']) : 'frontpage';

        /*
            Generating Actions class filename (example: HomeActions) and path to
            that class (example: home/HomeActions.php5), checking if $file is a
            valid file, and then, if so, requiring that file.
        */
        $class = ucfirst($module) . 'Actions';
        $file  = $this->pageDir . '/' . $module . '/' . $class . '.php5';

        if (!is_file($file)) {
            throw new FrontControllerException('Page not found!');
        }

        require_once $file;

        /*  
            Creating a new instance of the Actions class (example: $controller
            = new HomeActions(), and passing page directory variable to the
            ActionController class.
        */
        $controller = new $class();
        $controller->setRegistry($this->registry);

        try {
            //Using the setModule method in the ActionController class
            $controller->setModule($module);

            /*
                The ActionController dispatchAction method checks if the method
                exists, then runs the displayView function in the
                ActionController class.
            */    
            $controller->dispatchAction($action);
        }
        catch(Exception $error) {

            /*
                An exception has occurred, and will be displayed if
                $throwExceptions is set to true.
            */
            if($throwExceptions) {
                echo $error->errorMessage($error); //Full exception echoed
            } else {
                echo $error->errorMessage(null); //Simple error messaged echoed
            }
        }
    }
}

abstract class ActionController {

    //Declaring variable(s)
    protected $registry;
    protected $module;
    protected $viewData = array();
    
    //Class construct method
    public function __construct(){}
    
    public function setRegistry($registry) {
        
        //Sets the registry object
        $this->registry = $registry;
        
        /* Once the registry is loaded, the MVC root directory path is set from
         * the registry.  This path is needed for the MVC classes to work
         * properly.
         */
        $this->setPageDir();
        
        /* Setting variables for objects external to the MVC that are used in
         * multiple modules.  These objects add NO functionality to the actual
         * MVC classes, but are used by multiple modules.
         */
        $this->auth = $this->registry->get('auth'); //User authentication object
    }
    
    //Sets the MVC root directory from the value stored in the registry
    public function setPageDir() {
        $this->pageDir = $this->registry->get('pageDir');
    }

    //Sets the module
    public function setModule($module) {
        $this->module = $module;
    }

    //Gets the module
    public function getModule() {
        return $this->module;
    }

    //Placing a value in the $viewData array at the key position
    public function setVar($key, $value) {
        $this->viewData[$key] = $value;
    }

    //Returns a value from the $viewData array located at the key position
    public function getVar($key) {
        if (array_key_exists($key, $this->viewData)) {
            return $this->viewData[$key];
        }
    }

    //Gets the viewData array
    public function getViewData($viewData) {
        $this->viewData = $viewData;
    }

    /*
        Checking for actionMethod in the Actions class (example: doFrontpage()
        within home/HomeActions.php5) with the method_exists function and, if
        present, the actionMethod and displayView functions are executed.
    */  
    public function dispatchAction($action) {
        $actionMethod = 'do' . ucfirst($action);
        if (!method_exists($this, $actionMethod)) {
            throw new FrontControllerException('Page not found!');
        }
        $this->$actionMethod();
        $this->displayView($action);
    }

    public function displayView($action) {
        if (!is_file($this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php5')) {
            throw new FrontControllerException('Page not found!');
        }

        //Setting $this->actionView to the path of the action View file
        $this->actionView = $this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php5';

        /*
            Creating a new instance of the View class and passing the $pageDir,
            $viewData, and actionView variables
        */  
        $view = new View();
        $view->setRegistry($this->registry);
        $view->getViewData($this->viewData);
        $view->setVar('actionView',$this->actionView);
        $view->render();
    }
}

class View extends ActionController {

    public function render() {

        //Including default template settings
        require_once $this->pageDir . '/defaultTplSettings.php5';

        /*
            Merging the default template variables with variables provided in
            the $this->viewData array, taken from the Actions class, giving
            priority to those provided by the action class, then extracting the
            array with the extract() function, which creates a variable for
            every array value, and the name of the value (the variable name) is
            the key's value.
        */
        $templateSettings = array_merge($defaultTemplateSettings, $this->viewData);
        extract($templateSettings, EXTR_OVERWRITE);

        //Including template file within which the action View file is included
        require_once $this->pageDir . '/default.tpl';
    }
}

class FrontControllerException extends Exception {
    public function errorMessage($error) {
        
        /*
            If and throwExceptions is true, then the full exception will be
            returned.
        */
        $errorMessage = isset($error) ? $error : $this->getMessage();
        return $errorMessage;
    }
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.