Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
I am still very new to PHP, and am creating a simple MVC front controller. Everything works, but I have an ActionController class that basically contains my MVC "View" functionality within the displayView() function. I want to split the following class into (1) an ActionController class and (2) View class. Will you show me how you would split this class into those? What subclasses would you include where? I guess this is an opinion/best practice question. I just want to make sure I am keeping my business and presentation logic separated.
<?php
abstract class ActionController {
//Declaring variables
protected $name;
protected $viewData = array();
protected $content;
private static $pageDir;
//Setting the page directory, which is passed from the FrontController
public static function setPageDir($pageDir){
self::$pageDir = $pageDir;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
//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];
}
}
/*
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("Action Method not found!");
}
$this->$actionMethod();
$this->displayView($action);
}
public function displayView($action) {
if (!is_file(self::$pageDir . "/" . $this->getName() . "/" . $action . "View.php5")) {
throw new FrontControllerException("Action View not found!");
}
//This foreach function goes over all of the elements in $this->viewData array, creates
//a variable for every value, and the name of the value (the variable name) is the key's value.
foreach ($this->viewData as $key => $value) {
$$key = $value;
}
//Setting content variable to the path of the action View file
$this->content = self::$pageDir . "/" . $this->getName() . "/" . $action . "View.php5";
//Including a template file within which the action View file is included
require_once self::$pageDir . "/template.php5";
}
public function __set($key, $value) {
$this->setVar($key, $value);
}
public function __get($key) {
return $this->getVar($key);
}
}
?>