cgm225 Posted August 16, 2008 Share Posted August 16, 2008 I have an MVC in which I have modules that have action classes. Below I have included one such action class, with two functions with some redundant code found at the start of both of them (doNotes() and doNote()), like where I include the Notes class and connect to the database. Therefore, because the MVC calls those functions directly, I tried to add a constructor to put that redundant code within (thus, only including it once) but that did not work. Is there anyway to remove the redundant code within this class and put it somewhere else only once? I just want to do this well. Also, ANY other feedback is greatly appreciated! <?php class NotesActions extends ActionController { public function doNotes() { //Adds page title to registry $this->registry->set('title', 'Example.com "Năstase" edition: Notes'); //Sets MySQLi connection object and selects database $mysqli = $this->registry->get('mysqli'); $mysqli->select_db('example_db'); //Includes then instatiates new Notes class require_once $this->pageDir . '/' . $this->getModule() . '/' . 'includes/NotesClass.php5'; $notes = new Notes($mysqli); //Gathers all entries from the database and puts them into an array $notes->findEntries(); //Adds total number of entries to the registry $this->registry->set('totalEntries', $notes->getDataCount()); //Sets page variable $regex = '/[^0-9]++/'; //Only numbers allowed $page = isset($_GET['page']) ? preg_replace($regex, '', $_GET['page']) : 1; /* Includes & instantiates class to specify number of items displayed * per page */ require_once $this->pageDir . '/' . $this->getModule() . '/' . 'includes/NumberDisplayedClass.php5'; $numberDisplayed = new NumberDisplayed(); /* If user has selected a new number to display from a dropdown menu * form, that value will be added/updated in the numberDisplayed session * variable. If no new value has been provided, then, if the key is * present, the existing session variable key/value pair will be used, * or a new pair will be created based on a privided default value */ if (isset($_POST['numberDisplayed'])) { $numberDisplayed->setNumberDisplayed('notes', $_POST['numberDisplayed']); } elseif (!$numberDisplayed->getNumberDisplayed('notes')) { $numberDisplayed->setNumberDisplayed('notes', 3); //Sets default } //Adds numberDisplayed variable to the registry $numberDisplayed = $numberDisplayed->getNumberDisplayed('notes'); $this->registry->set('notesDisplayed', $numberDisplayed); //Calculates total number of pages and adds value to the registry $totalPages = ceil($notes->getDataCount() / $numberDisplayed); $this->registry->set('totalPages', $totalPages); /* Resets page number to total number of pages if current page value is * greater than total pages */ $page = ($page > $totalPages) ? $totalPages : $page; //Adds final page value to the registry $this->registry->set('page', $page); /* Calculates position of the first and last entry within the data array * for any partciular page and adds those values to the registry */ $firstPageEntry = ($page * $numberDisplayed) - $numberDisplayed; $lastPageEntry = $firstPageEntry + $numberDisplayed; $this->registry->set('firstPageEntry ', $firstPageEntry); $this->registry->set('lastPageEntry', $lastPageEntry); //Passes data array to the registry $this->registry->set('notes', $notes->getSlicedData($firstPageEntry, $numberDisplayed)); } public function doNote() { //Adds page title to registry $this->registry->set('title', 'Example.com "Năstase" edition: Note'); //Sets entry variable and adds to registry $regex = '/[^-_A-z0-9]++/'; //Allowed characters: letter, number, underscore or hyphen $entry = isset($_GET['entry']) ? preg_replace($regex, '', $_GET['entry']) : null; $this->registry->set('entry', $entry); //Sets MySQLi connection object and selects database $mysqli = $this->registry->get('mysqli'); $mysqli->select_db('example_db'); //Includes then instatiates new Notes class require_once $this->pageDir . '/' . $this->getModule() . '/' . 'includes/NotesClass.php5'; $notes = new Notes($mysqli); //Gathers all entries from the database and puts them into an array $notes->findEntries(); //Sets the entry data array into registry $this->registry->set('notes', $notes->getData()); } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/119941-removing-redundancy-in-module-class/ Share on other sites More sharing options...
ignace Posted August 16, 2008 Share Posted August 16, 2008 protected function _doNote($note) {} public function doNotes() { foreach ($notes $as $note) $this->_doNote($note); } public function doNote() { $this->_doNote($someNote); } for more on this do a read up on refactoring, btw your NotesActions is a wrong MVC implementation, you are currently doing VC without the M (Microsoft's MVC implementation as found in VB, where controller and model seems to be the same thing), your controller should only delegate calling required models to do all calculations, fetch data, etc.. and decide which view to use for rendering, the view then renders the data from the model for which it may use view helpers if to complex to render Quote Link to comment https://forums.phpfreaks.com/topic/119941-removing-redundancy-in-module-class/#findComment-617972 Share on other sites More sharing options...
cgm225 Posted August 16, 2008 Author Share Posted August 16, 2008 Thank you so much for your feedback. I am new to OOP and MVC, therefore, I did not completely follow everything you wrote. Would you mind explaining your feedback a little more? Regardless, thanks again! Also, I have posted my index and MVC class below, just in case you want to see what I am doing... Index.php <?php //Initializing session session_start(); //General configurations require_once 'configurations.php5'; //Instatiating MySQLi object for all modules with NO database selected. $mysqli = new mysqli(MYSQL_SERVER, MYSQL_SERVER_USERNAME, MYSQL_SERVER_PASSWORD); //Additional includes require_once MVC_ROOT . '/Authentication.php5'; //User authentication require_once MVC_ROOT . '/RegistryItems.php5'; //Default registry items require_once MVC_ROOT . '/ModelViewController.php5'; //MVC with registry class //Instantiating registry object $registry = new Registry(); $registry->addRegistryArray($registryItems); //Instantiating front controller object $controller = FrontController::getInstance(); $controller->setRegistry($registry); $controller->dispatch(false); //Closing MySQLi object $mysqli->close(); ?> ModelViewController.php5 <?php class FrontController extends ActionController { //Declaring variable(s) private static $instance; protected $controller; //Class construct method public function __construct() {} //Starts 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) { /* Checks for the GET variables $module and $action, and, if present, * strips 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'; /* Generates Actions class filename (example: HomeActions) and path to * that class (example: home/HomeActions.php5), checks if $file is a * valid file, and then, if so, requires 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; /* Creates a new instance of the Actions class (example: $controller * = new HomeActions(), and passes the registry variable to the * ActionController class. */ $controller = new $class(); $controller->setRegistry($this->registry); try { //Trys 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 $registryItems = 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(); } //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; } /* Checks 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!'); } //Sets $this->actionView to the path of the action View file $this->actionView = $this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php5'; //Sets path of the action View file into the registry $this->registry->set('actionView', $this->actionView); //Includes template file within which the action View file is included require_once $this->pageDir . '/default.tpl'; } } class Registry { //Declaring variables private $store; //Class constructor public function __construct() {} //Sets registry variable public function set($label, $object) { $this->store[$label] = $object; } //Gets registry variable public function get($label) { if(isset($this->store[$label])) { return $this->store[$label]; } return false; } //Adds outside array of registry values to $this->store array public function addRegistryArray($registryItems) { foreach ($registryItems as $key => $value) { $this->set($key, $value); } } //Returns registry array public function getRegistryArray() { return $this->store; } } class FrontControllerException extends Exception { public function errorMessage($error) { //If and throwExceptions is true, then the full exception is returned. $errorMessage = isset($error) ? $error : $this->getMessage(); return $errorMessage; } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/119941-removing-redundancy-in-module-class/#findComment-617994 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.