Using $config array in MVC classes - php

I've done quite a bit of reading on this and a lot of people are saying I should be using a singleton class. I was thinking of writing a "Config" class which would include a "config.php" file on __construct and loop through the $config array values and place them into $this->values...
But then I read more and more about how singletons should never be used. So my question is - what is the best approach for this? I want to have a configuration file, for organization purposes, that contains all of my $config variables. I do not want to be hardcoding things such as database usernames and passwords directly into methods, for the purpose of flexibility and whatnot.
For example, I use the following code in an MVC project I am working on:
public/index.php
<?php
include '../app/bootstrap.php';
?>
app/bootstrap.php
<?php
session_start();
function __autoload ($class) {
$file = '../app/'.str_replace('_', '/', strtolower($class)).'.php';
if (file_exists($file)) {
include $file;
}
else {
die($file.' not found');
}
}
$router = new lib_router();
?>
app/lib/router.php
<?php
class lib_router {
private $controller = 'controller_home'; // default controller
private $method = 'index'; // default method
private $params = array();
public function __construct () {
$this->getUrl()->route();
}
private function getUrl () {
if (isset($_GET['url'])) {
$url = trim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
$this->controller = isset($url[0]) ? 'controller_'.ucwords($url[0]) : $this->controller;
$this->method = isset($url[1]) ? $url[1] : $this->method;
unset($url[0], $url[1]);
$this->params = array_values($url);
}
return $this;
}
public function route () {
if (class_exists($this->controller)) {
if (method_exists($this->controller, $this->method)) {
call_user_func(array(new $this->controller, $this->method), $this->params);
}
else {
die('Method '.$this->method.' does not exist');
}
}
else {
die('Class '.$this->controller.' does not exist');
}
}
}
?>
Now let's say I visit http://localhost/myproject/lead/test
It is going to call the controller_lead class and the test method within.
Here is the code for app/controller/lead
<?php
class controller_lead extends controller_base {
public function test ($params) {
echo "lead test works!";
}
}
?>
app/controller/base
<?php
class controller_base {
private $db;
private $model;
public function __construct () {
$this->connect()->getModel();
}
private function connect () {
//$this->db = new PDO($config['db_type'] . ':host=' . $config['db_host'] . ';dbname=' . $config['db_name']. ', $config['db_user'], $config['db_pass'], $options);
return $this;
}
private function getModel () {
$model = str_replace('controller', 'model', get_class($this));
$this->model = new $model($this->db);
}
}
?>
This is where I run into the issue. As you can see, the connect method is going to try and create a new PDO object. Now how am I going to inject this $config variable, given all the other code I just provided?
My options appear to be:
Use a singleton (bad)
Use a global (worse)
Include config.php in bootstrap.php, and inject it throughout multiple classes (Why should I inject this into my lib_router class when lib_router has absolutely nothing to do with the database? This sounds like terrible practice.)
What other option do I have? I don't want to do any of those 3 things...
Any help would be greatly appreciated.

I ended up including a config file in my bootstrap which simply contained constants, and used the constants.

I ended up including a config file in my bootstrap which simply contained constants, and used the constants.
That was the same case for me - required the file in Model. The file based approach was the best fit since it has some benefits: you can .gitignore, set custom permission set, all your parameters are stored centrally, etc.
However, If the config file contains DB connection parameters only, I prefered to require the config file in Model only. Maybe, you could also break down into multiple, more specific config files and require them where necessary.
public function __construct()
{
if (self::$handle === FALSE)
{
$db = array();
require APP_DIR.DIR_SEP.'system'.DIR_SEP.'config'.DIR_SEP.'Database.php';
if (!empty($db))
{
$this->connect($db['db_host'], $db['db_user'], $db['db_password'], $db['db_name']);
}
else
{
Error::throw_error('Abimo Model : No database config found');
}
}
}

Related

PHP - Autoload only needed classes

I have an autoloader that is placed as a php file above all other sub directories in my project.
What it does is it loads all possible classes at once for any specific server request. After further thought I concluded I need to autoload only the required classes.
What do I need to do to avoid loading other classes not needed?
If I need to post the relevant code snippets of the class files in my subdirectories, I can.
<?php
namespace autoloader;
class autoloader
{
private $directoryName;
public function __construct($directoryName)
{
$this->directoryName = $directoryName;
}
public function autoload()
{
foreach (glob("{$this->directoryName}/*.class.php") as $filename)
{
include_once $filename;
}
foreach (glob("{$this->directoryName}/*.php") as $filename)
{
include_once $filename;
}
}
}
# nullify any existing autoloads
spl_autoload_register(null, false);
# instantiate the autoloader object
$classes = [
new autoloader('request'),
new autoloader('config'),
new autoloader('controllers'),
new autoloader('models'),
new autoloader('data')
];
# register the loader functions
foreach ($classes as $class)
spl_autoload_register(array($class, 'autoload'));
All registered autoloader functions will be called when you try to instantiate a new class or until it finally loads the class or throws an error. The way you have it now, you're registering the same autoloader function again and again for each directory, and file.
What you'd want to do is something along the lines of this.
namespace autoloader;
class autoloader
{
public function __construct()
{
spl_autoload_register([$this, 'autoload']);
}
public function autoload($classname)
{
if (! file_exists("{$classname}.class.php")) {
return;
}
include_once "{$classname}.class.php";
}
}
new autoloader();
Every autoloader function gets the class FQCN passed into it, and from there you'll have to parse it and figure out if you can load the file where that class exists. For instance, if I do the following.
use Some\Awesome\ClassFile;
$class = new ClassFile();
The autoloader we've registered will get the string Some\Awesome\ClassFile passed in as an argument, which we can then parse and see if we have a file for that class, if we don't we return out of the function and let the next registered autoloader function try and find the class.
You can read more about autoloaders in the documentation, I also wrote a blog post about it like 2 months ago that might interest you.
I had to refactor the code and remove the unnecessary load all functionality that I mistakenly thought would lazy load my classes on request.
Here is what I came up with:
Entry Point
<?php
require_once 'enums.php';
require_once 'api.class.php';
spl_autoload('AutoLoader\AutoLoader');
use App\API;
class MyAPI extends API
{
public function __construct($request){
parent::__construct($request);
}
}
$api = new MyAPI($_REQUEST);
echo $api->processRequest();
AutoLoader Implementation (located under subdirectory Autoloader/Autoloader.php and inaccessible via browser by using .htaccess)
<?php
namespace Autoloader;
spl_autoload_register("AutoLoader\AutoLoader::ClassLoader");
spl_autoload_register("AutoLoader\AutoLoader::RequestLoader");
class Autoloader
{
public static function ClassLoader(String $fileName)
{
foreach ([".Class.php", ".php"] as $extension)
if (file_exists($fileName.$extension))
include $fileName.$extension;
}
public static function RequestLoader()
{
self::ClassLoader('Request');
}
}
Snippet for processRequest() (located in api.class.php - my request router)
public function processRequest()
{
$id1 = $this->requestObj->id1;
$id2 = $this->requestObj->id2;
$endpoint1 = $this->requestObj->endpoint1;
$endpoint2 = $this->requestObj->endpoint2;
$goto = $this->requestObj->goto;
$isDestination = in_array($id1, ['first', 'prev', 'next', 'last']);
$numSetEndpoints = (int)isset($endpoint1) + (int)isset($endpoint2);
switch($numSetEndpoints)
{
case 0:
if ($isDestination)
return json_decode($this->_response("No Endpoint: ", $endpoint1));
return json_decode($this->_response("No Endpoint: " . $endpoint2 ?? $endpoint));
case 1:
$className = $endpoint1.'Controller';
break;
case 2:
$className = $endpoint2.'Controller';
break;
}
$class = "\\Controllers\\$className";
if (class_exists($class))
{
$method = strtolower($this->method);
if (method_exists($class, $method))
{
$response = (new $class($this->requestObj))->{$method}();
if ($response['Succeeded'] == false)
{
return $response['Result'];
}
else if ($response['Succeeded'] == true)
{
header("Content-Type: application/json");
return $this->_response($response);
}
else if ($response['Result'])
{
header("Content-Type: text/html");
return $this->_response($response);
}
}
}
}

PHP autoloading helpers inside a class

I currently have a manual method for registering helpers into my base connection class which goes pretty much as follows:
class db_con
{
// define the usual suspect properties..
public $helpers; // helper objects will get registered here..
public function __construct()
{
// fire up the connection or die trying
$this->helpers = (object) array();
}
public function __destruct()
{
$this->helpers = null;
$this->connection = null;
}
// $name = desired handle for the helper
// $helper = name of class to be registered
public function register_helper($name, $helper)
{
if(!isset($this->helpers->$name, $helper))
{
// tack on a helper..
$this->helpers->$name = new $helper($this);
}
}
// generic DB interaction methods follow..
}
Then a helper class such as..
class user_auth
{
public function __construct($connection){ }
public function __destruct(){ }
public function user_method($somevars)
{
// do something with user details
}
}
So after creating the $connection object, i would then manually register a helper like so:
$connection->register_helper('users', 'user_auth');
Now my question is, could I somehow autoload helper classes inside the base connection class? (within the register_helper() method or similar) Or am I limited to loading them manually or via an external autoloader of some form?
My apologies if this question has been answered elsewhere, but I just haven't found it (not for lack of trying) and I haven't any real experience autoloading anything yet.
Any help or pointers greatly appreciated, thanks in advance! :)
EDIT: As per Vic's suggestion this is the working solution I came up with for the register method..
public function register_handlers()
{
$handler_dir = 'path/to/database/handlers/';
foreach (glob($handler_dir . '*.class.php') as $handler_file)
{
$handler_bits = explode('.', basename($handler_file));
$handler = $handler_bits[0];
if(!class_exists($handler, false))
{
include_once $handler_file;
if(!isset($this->handle->$handler, $handler))
{
$this->handle->$handler = new $handler($this);
}
}
}
}
This appears to include and register the objects absolutely fine for now, whether this solution is a "good" one or not, I can't know without more input or testing.
The code could look something like below, but why would you need this?
public function register_helper($name, $helper)
{
if(!isset($this->helpers->$name, $helper))
{
$this->load_class($helper);
// tack on a helper..
$this->helpers->$name = new $helper($this);
}
}
private function load_class($class)
{
if( !class_exists($class, false) ) {
$class_file = PATH_SOME_WHERE . $class . '.php';
require $class_file;
}
}

Assigning defaults for Smarty using Object Oriented style

I'm just very slowly starting to sink into object-oriented programming, so please be gentle on me.
I have a custom class for Smarty that was partially borrowed. This is how the only example reflects the basic idea of using it across my current project:
class Template {
function Template() {
global $Smarty;
if (!isset($Smarty)) {
$Smarty = new Smarty;
}
}
public static function display($filename) {
global $Smarty;
if (!isset($Smarty)) {
Template::create();
}
$Smarty->display($filename);
}
Then in the PHP, I use the following to display templates based on the above example:
Template::display('head.tpl');
Template::display('category.tpl');
Template::display('footer.tpl');
I made the following example of code (see below) work across universally, so I wouldn't repeat the above lines (see 3 previous lines) all the time in each PHP file.
I would just like to set, e.g.:
Template::defauls();
that would load:
Template::display('head.tpl');
Template::display('template_name_that_would_correspond_with_php_file_name.tpl');
Template::display('footer.tpl');
As you can see Template::display('category.tpl'); will always be changing based on the PHP file, which name is corresponded with the template name, meaning, if for example, PHP file is named stackoverflow.php then the template for it would be stackoverflow.tpl.
I've tried my solution that have worked fine but I don't like it the way it looks (the way it's structured).
What I did was:
Assigned in config a var and called it $current_page_name (that derives the current PHP page name, like this: basename($_SERVER['PHP_SELF'], ".php"); ), which returned, for e.g.: category.
In PHP file I used Template::defaults($current_page_name);
In my custom Smarty class I added the following:
public static function defaults($template) {
global $Smarty;
global $msg;
global $note;
global $attention;
global $err;
if (!isset($Smarty)) {
Templates::create();
}
Templates::assign('msg', $msg);
Templates::assign('note', $note);
Templates::assign('attention', $attention);
Templates::assign('err', $err);
Templates::display('head.tpl');
Templates::display($template . '.tpl');
Templates::display('footer.tpl');
}
Is there a way to make it more concise and well structured? I know about Code Review but I would like you, guys, to take a good look at it.
This looks like you haven't loaded Smarty, that's why the error happens. You need to start by including Smarty before the class starts. If you follow my other config suggestion you should start by including that one as well.
In you Template class, just add the following function:
function defaults() {
// Don't know if you need the assignes, havn't used Smarty, but if so, insert them here...
Template::display( Config::get('header_template') ); //header_template set in the Config file
Template::display( basename($_SERVER['PHP_SELF'], ".php") . '.tpl' );
Template::display( Config::get('footer_template') ); //footer_template set in the Config file
}
Now you should be able to use it in any file:
$template = new Template();
$template->defaults();
EDIT:
A singleton is in every sense the same as a global, that will keep your same problem.
But your problem is that if you try to use one of the Template's static functions you are in the "static" mode, which means the constructor have not been run. And Smarty has not been assigned. If you want to go this road, you can do one of two thinks:
Make the Template a real singleton, meaning set the constructor to private add a function getInstance, that returns a instance of the class, and then use that object to call the functions in it (which should not be static), or
Make all those static functions check if smarty is set, and if it's not, create a new instance of smarty, otherwise use the one that already is instantiated to run its function.
EDIT 2:
Here's the proper way to make a singleton:
class Singleton {
private static $instance = null;
// private static $smarty = null;
private function __construct() {
//self::$smarty = new Smarty();
}
public static function getInstance() {
if( self::$instance === null ) {
self::$instance = self();
}
return self::$instance;
}
public function doSomething() {
//self::$smarty->doSomething();
}
}
It's used like this:
$singleton = Singletong::getInstance();
$singleton->doSomething();
I commented out the things you probably want do to to make this a singleton wrapper around a singleton Smarty object. Hope this helps.
EDIT 3:
Here's a working copy of your code:
class Template {
private static $smarty_instance;
private static $template_instance;
private function Template() {
self::$smarty_instance = new Smarty();
$this->create();
}
public static function getInstance() {
if( ! isset( self::$template_instance ) ) {
self::$template_instance = new self();
}
return self::$template_instance;
}
private function create() {
self::$smarty_instance->compile_check = true;
self::$smarty_instance->debugging = false;
self::$smarty_instance->compile_dir = "/home/docs/public_html/domain.org/tmp/tpls";
self::$smarty_instance->template_dir = "/home/docs/public_html/domain.org";
return true;
}
public function setType($type) {
self::$smarty_instance->type = $type;
}
public function assign($var, $value) {
self::$smarty_instance->assign($var, $value);
}
public function display($filename) {
self::$smarty_instance->display($filename);
}
public function fetch($filename) {
return self::$smarty_instance->fetch($filename);
}
public function defaults($filename) {
global $user_message;
global $user_notification;
global $user_attention;
global $user_error;
self::$smarty_instance->assign('user_message', $user_message);
self::$smarty_instance->assign('user_notification', $user_notification);
self::$smarty_instance->assign('user_attention', $user_attention);
self::$smarty_instance->assign('user_error', $user_error);
self::$smarty_instance->assign('current_page', $filename);
self::$smarty_instance->display('head.tpl');
self::$smarty_instance->display($filename . '.tpl');
self::$smarty_instance->display('footer.tpl');
}
}
When using this function, you should use it like this:
$template = Template::getInstance();
$template->defaults($filename);
Try it now.
You can get current file name in your defaults() function. Use this piece of code:
$currentFile = $_SERVER['REQUEST_URI'];
$parts = explode('/', $currentFile);
$fileName = array_pop($parts);
$viewName = str_replace('.php', '.tpl', $fileName);
$viewName is the name that you need.
This is a quick wrapper I made for Smarty, hope it gives you some ideas
class Template extends Smarty
{
public $template = null;
public $cache = null;
public $compile = null;
public function var($name, $value, $cache)
{
$this->assign($name, $value, $cache);
}
public function render($file, $extends = false)
{
$this->prep();
$pre = null;
$post = null;
if ($extends)
{
$pre = 'extends:';
$post = '|header.tpl|footer.tpl';
}
if ($this->prep())
{
return $this->display($pre . $file . $post);
}
}
public function prep()
{
if (!is_null($this->template))
{
$this->setTemplateDir($this->template);
return true;
}
if (!is_null($this->cache))
{
$this->setCacheDir($this->cache);
}
if (!is_null($this->compile))
{
$this->setCompileDir($this->compile);
return true;
}
return false;
}
}
Then you can use it like this
$view = new Template();
$view->template = 'path/to/template/';
$view->compile = 'path/to/compile/'
$view->cache = 'path/to/cache';
$view->assign('hello', 'world');
// or
$view->var('hello', 'world');
$view->render('index.tpl');
//or
$view->render('index.tpl', true); // for extends functionality
I did this kinda fast, but just to show you the basic ways you can use smarty. In a more complete version you could probably want to check to see if compile dir is writable, or if file templates exist etc.
After trying for few days to solve this simple problem, I have finally came up with working and fully satisfying solution. Remember, I'm just a newby in object-oriented programming and that's the main reason why it took so long.
My main idea was not to use global $Smarty in my initial code that worked already fine. I like to use my Smarty as just simple as entering, e.g.: Template::assign('array', $array). To display defaults, I came up with the trivial solution (read my initial post), where now it can be just used Template::defaults(p()); to display or assign anything that is repeated on each page of your project.
For doing that, I personally stopped on the following fully working solution:
function p() {
return basename($_SERVER['PHP_SELF'], ".php");
}
require('/smarty/Smarty.class.php');
class Template
{
private static $smarty;
static function Smarty()
{
if (!isset(self::$smarty)) {
self::$smarty = new Smarty();
self::Smarty()->compile_check = true;
self::Smarty()->debugging = false;
self::Smarty()->plugins_dir = array(
'/home/docs/public_html/domain.com/smarty/plugins',
'/home/docs/public_html/domain.com/extensions/smarty');
self::Smarty()->compile_dir = "/home/docs/public_html/domain.com/cache";
self::Smarty()->template_dir = "/home/docs/public_html/domain.org";
}
return self::$smarty;
}
public static function setType($type)
{
self::Smarty()->type = $type;
}
public static function assign($var, $value)
{
self::Smarty()->assign($var, $value);
}
public static function display($filename)
{
self::Smarty()->display($filename);
}
public static function fetch($filename)
{
self::Smarty()->fetch($filename);
}
public static function defaults($filename)
{
Template::assign('current_page_name', $filename);
Template::display('head.tpl');
Template::display($filename . '.tpl');
Template::display('footer.tpl');
}
}
Please use it if you like it in your projects but leave comments under this post if you think I could improve it or you have any suggestions.
Initial idea of doing all of that was learning and exercising in writing a PHP code in object-oriented style.

Which is the best practice to access config inside a function?

<?php
define('ABSPATH', dirname(__FILE__)); //Absolute path to index
/*
* Method 1
* Dependency Injection
*/
class Config{
private $_config = NULL;
private $_filepath = NULL;
public function __construct($filepath){
$this->_filepath = $filepath;
$this->load();
}
private function load(){
if ($this->_config === NULL){
if (!file_exists($this->_filepath)){
throw new Exception('Configuration file not found');
}else{
$this->_config = parse_ini_file($this->_filepath);
}
}
}
public function get($key){
if ($this->_config === NULL){
throw new Exception('Configuration file is not loaded');
}
if (isset($this->_config[$key])){
return $this->_config[$key];
}else{
throw new Exception('Variable ' . $key . ' does not exist in configuration file');
}
}
}
function getLost($where, $why, $who){
//do smth
}
try{
$config = new Config(ABSPATH . '/app/config.ini');
getLost('here', 'because', $config->get('who'));
}catch(Exception $e){
echo $e->getMessage();
}
?>
<?php
/*
* Method 2
* Config is accessed via static class
*/
class Config{
private static $_config = NULL;
private static $_filepath = NULL;
public static function load($filepath){
if (self::$_config === NULL){
self::$_filepath = $filepath;
if (!file_exists(self::$_filepath)){
throw new Exception('Configuration file not found');
}else{
self::$_config = parse_ini_file(self::$_filepath);
}
}
}
public static function get($key){
if (self::$_config !== NULL){
throw new Exception('Configuration file is not loaded');
}
if (isset(self::$_config[$key])){
return self::$_config[$key];
}else{
throw new Exception('Variable ' . $key . ' does not exist in configuration file');
}
}
}
function getLost($where, $why){
$who = Config::get('who');
}
try{
Config::load(ABSPATH . '/app/config.ini');
getLost('here', 'because');
}catch(Exception $e){
echo $e->getMessage();
}
?>
<?php
/**
* Method 3
* Config variable needed is passed as function parameter
*/
$config = parse_ini_file(ABSPATH . '/app/config.ini');
function getLost($where, $why, $who){
//do smth
}
getLost('here', 'because', $config['who']);
?>
<?php
/*
* Mathod 4
* Config is accessed inside a function via global
*/
$config = parse_ini_file(ABSPATH . '/app/config.ini');
function getLost($where, $why){
global $config;
$who = $config['who'];
}
getLost('here', 'because');
?>
Which of these variants is the best practice solution? If none, please provide your variant.
I would go for variant 1 (dependency injection).
Variant 2 uses static methods which are as already stated just enother way of global methods. And we all know that is bad right? right?
Variant 3 isn't me favorite because it's not OOP enough ;-), but serious: what if you (or the person using your code) wants to change the format of the config file?
Variant 4: global...
So basically my issues with other options are: testability, tight coupling, global.
So variant 1 it is. I would also create an interface for the config class so you may add a different class for your config stuff at a later point. E.g. you (or someone else for that matter) wants to use XML files for config.
Another thing I would change is private stuff. If someone wants to extend the class he/she wouldn't have access to the variables this way. My rule of thumb (not sure if everybody agrees with this though) is only make stuff private if you want people to have access to it (e.g. it will change at some point). The danger of using private is that people will get around it by hacks to do what they want.
Read more about SOLID and see the Google clean code talks for more info.
Just my 2 cents.
I'd say first case is better if you replace $config with $onlyTheStuffThatMattersToThatFunction

How does this control architecture script look?

I am looking for feedback on my control architecture script (included below). Specifically, I am looking for feedback regarding the script's design, organization, commenting, and formatting. I enjoy php programming as a hobby, and am looking to learn where I can improve my code.
Thanks in advance!
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.php), checks if $file is a
* valid file, and then, if so, requires that file.
*/
$class = ucfirst($module) . 'Actions';
$file = $this->pageDir . '/' . $module . '/' . $class . '.php';
try {
//Checks for existance of file
if (!is_file($file)) {
throw new Exception('File not found!');
}
//Includes file
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);
//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;
}
}
}
}
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 controller root directory path is
* set from the registry. This path is needed for the controller
* classes to work properly.
*/
$this->setPageDir();
}
//Sets the controller 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.php) 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 Exception('Action not found!');
}
$this->$actionMethod();
$this->displayView($action);
}
public function displayView($action) {
if (!is_file($this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php')) {
throw new Exception('View not found!');
}
//Sets $this->actionView to the path of the action View file
$this->actionView = $this->pageDir . '/' . $this->getModule() . '/' . $action . 'View.php';
//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];
} else {
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;
}
}
Without having a detailed look on your code:
Try to write code that is self-explanatory by using meaningful function and variable names. Only use comments where the purpose or the functioning of your code is not clear. E.g.
//Declaring variable(s)
//Class construct method
//Checks for existance of file
//Includes file
are useless comments because the code itself is already clear enough.
A book worth reading: Clean Code
I am torn between closevoting as too localized and wanting to comment on the code. Also, it's too much code to wade through now, so I will comment only a few things:
1) Documentation style
Why not use an established documentation format, like PHPDoc?
2) Formatting
is consistent as far as I can see, but I suggest to use a coding convention that is in wide use, like that of PEAR or ZF (which is based on PEAR) instead of doing your own (yours is close to PEAR anyway, so you might as well adopt it completely).
3) Singleton pattern
In order for the Singleton to work it has to have a private __contruct and __clone method. But I suggest not to use it at all. Many people believe the Singleton is an AntiPattern. There are a number of questions on SO discussing the disadvantages of the Singleton pattern, so have a look around. If there should be only one instance, then simply dont instantiate a second one. If you need to access the FrontController in other classes, inject it.
4) Method length
I probably would try to shorten the dispatch method. Basically, if you describe what a method does and you have to use an and to do so, that part should go into it's own method. Try to make methods into small discrete units. That will make UnitTesting easier as well.
5) Separation of Concerns
I am not sure why the FrontController extends from ActionController. There is no other classes that extent it, butI suppose the classes the FrontController instantiates are subclasses of ActionController too. But the FrontController, while named a controller, does different things than the PageControllers, so I'd probably keep them separated.
On a sidenote, if you are interested in increasing the quality of your code, have a look at the slides and tools given at http://phpqatools.org/
Your code is very remeiscent of CakePhp. I'd recommend checking that out, it does all of this work with App::import() and a File class that wraps the filesystem. It's tested by a community on different versions and OSes, it will in fact save you time.

Categories