Seems like this is a very common problem for beginners with CodeIgniter, but none of the solutions I've found so far seems very relevant to my problem. Like the topic says I'm trying to include a custom class in CodeIgniter.
I'm trying to create several objects of the class below and place them in an array, thus I need the class to be available to the model.
I've tried using the load (library->load('myclass') functions within CodeIgniter which sort of works, except it tries to create an object of the class outside the model first. This is obviously a problem since the constructor expects several parameters.
The solutions I've found so far is
A simple php include which seems fine enough, but since I'm new to
CodeIgniter I want to make sure I'm sticking to it as much as
possible.
Creating a "wrapper class" as suggested here, however I'm uncertain how I would implement this.
The class I want to include,
User.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User{
public $ID = 0;
public $username = 0;
public $access_lvl = 0;
public $staff_type = 0;
public $name = 0;
public function __construct($ID, $username, $access_lvl, $staff_type, $name)
{
$this->ID = $ID;
$this->username = $username;
$this->access_lvl = $access_lvl;
$this->staff_type = $staff_type;
$this->name = $name;
}
public function __toString()
{
return $this->username;
}
}
?>
Method (Model) which needs the User.php
function get_all_users()
{
$query = $this->db->get('tt_login');
$arr = array();
foreach ($query->result_array() as $row)
{
$arr[] = new User
(
$row['login_ID'],
$row['login_user'],
$row['login_super'],
$row['crew_type'],
$row['login_name']
);
}
return $arr;
}
And finally the controller,
function index()
{
$this->load->library('user');
$this->load->model('admin/usersmodel', '', true);
// Page title
$data['title'] = "Some title";
// Heading
$data['heading'] = "Some heading";
// Data (users)
$data['users'] = $this->usersmodel->get_all_users();
If you have PHP version >= 5.3 you could take use of namespaces and autoloading features.
A simple autoloader library in the library folder.
<?php
class CustomAutoloader{
public function __construct(){
spl_autoload_register(array($this, 'loader'));
}
public function loader($className){
if (substr($className, 0, 6) == 'models')
require APPPATH . str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php';
}
}
?>
The User object in the model dir. ( models/User.php )
<?php
namespace models; // set namespace
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User{
...
}
And instead of new User... new models\User ( ... )
function get_all_users(){
....
$arr[] = new models\User(
$row['login_ID'],
$row['login_user'],
$row['login_super'],
$row['crew_type'],
$row['login_name']
);
...
}
And in controller just make sure to call the customautoloader like this:
function index()
{
$this->load->library('customautoloader');
$this->load->model('admin/usersmodel', '', true);
// Page title
$data['title'] = "Some title";
// Heading
$data['heading'] = "Some heading";
// Data (users)
$data['users'] = $this->usersmodel->get_all_users();
CodeIgniter doesn't really support real Objects.
All the libraries, models and such, are like Singletons.
There are 2 ways to go, without changing the CodeIgniter structure.
Just include the file which contains the class, and generate it.
Use the load->library or load_class() method, and just create new objects. The downside of this, is that it will always generate 1 extra object, that you just don't need. But eventually the load methods will also include the file.
Another possibility, which will require some extra work, is to make a User_Factory library.
You can then just add the object on the bottom of the file, and create new instances of it from the factory.
I'm a big fan of the Factory pattern myself, but it's a decision you have to make yourself.
I hope this helped you, if you have any questions that are more related to the implementation, just let me/us know.
Including a class file is not a bad approach.
In our projects, we do the same, add an another layer to MVC, and thats a Service Layer which the Controllers calls and Service calls the Model. We introduced this layer to add Business Logic seperate.
So far, we have been using it, and our product has gone large too, and still we find no difficulty with the decision of including files that we had made in the past.
Codeigniter has a common function to instantiate individual classes.
It is called load_class(), found in /system/core/Common.php
The function;
/**
* Class registry
*
* This function acts as a singleton. If the requested class does not
* exist it is instantiated and set to a static variable. If it has
* previously been instantiated the variable is returned.
*
* #access public
* #param string the class name being requested
* #param string the directory where the class should be found
* #param string the class name prefix
* #return object
*/
The signature is
load_class($class, $directory = 'libraries', $prefix = 'CI_')
An example of it being used is when you call the show_404() function.
After a brief google search, I was inspired to make my own autoloader class. It's a bit of a hack, since I use custom Codeigniter library to preform auto-loading, but for me this is the best way, that I'm aware of, of loading all the classes, I require, without compromising my application architecture philosophy, to fit it into Codeigniter way of doing things. Some might argue that Codeigniter is not the right framework for me and that might be true, but I'm trying things out and playing around with various frameworks and while working on CI, I came up with this solution.
1. Auto-load new custom library by editing applicaion/config/autoload.php to include:
$autoload['libraries'] = array('my_loader');
and any other libraries you might need.
2. Then add library class My_loader. This class will be loaded on every request and when its constructor is run, it will recursively search through all sub-folders and require_once all .php files inside application/service & application/models/dto folders. Warning: folders should not have dot in the name, otherwise function will fail
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class My_loader {
protected static $_packages = array(
'service',
'models/dto'
);
/**
* Constructor loads service & dto classes
*
* #return void
*/
public function __construct($packages = array('service', 'models/dto'))
{
// files to be required
$toBeRequired = array();
// itrate through packages
foreach ($packages as $package) {
$path = realpath(APPPATH . '/' . $package . '/');
$toBeRequired = array_merge($toBeRequired, $this->findAllPhpFiles($path));
}
/**
* Require all files
*/
foreach ($toBeRequired as $class) {
require_once $class;
}
}
/**
* Find all files in the folder
*
* #param string $package
* #return string[]
*/
public function findAllPhpFiles($path)
{
$filesArray = array();
// find everithing in the folder
$all = scandir($path);
// get all the folders
$folders = array_filter($all, get_called_class() . '::_folderFilter');
// get all the files
$files = array_filter($all, get_called_class() . '::_limitationFilter');
// assemble paths to the files
foreach ($files as $file) {
$filesArray[] = $path . '/' . $file;
}
// recursively go through all the sub-folders
foreach ($folders as $folder) {
$filesArray = array_merge($filesArray, $this->findAllPhpFiles($path . '/' . $folder));
}
return $filesArray;
}
/**
* Callback function used to filter out array members containing unwanted text
*
* #param string $string
* #return boolean
*/
protected static function _folderFilter($member) {
$unwantedString = '.';
return strpos($member, $unwantedString) === false;
}
/**
* Callback function used to filter out array members not containing wanted text
*
* #param string $string
* #return boolean
*/
protected static function _limitationFilter($member) {
$wantedString = '.php';
return strpos($member, $wantedString) !== false;
}
}
After 18 hours I managed to include a library in my control without initialisation (the constructor was the problem, because of that and i could't use the standard codeiginiter $this->load->library() ).
Follow the https://stackoverflow.com/a/21858556/4701133 . Be aware for further native class initialization use $date = new \DateTime()with back-slash in front otherwise the function will generate an error !
Related
I'm new with CodeIgniter and I'd like to load a model in core/MY_Lang.php class.
class MY_Lang extends CI_Lang
{
/** array $languages Array of languages */
var $languages = array('');
/** array $special Special URIs (not localized) **/
var $special = array('');
/** string $default_uri Where to redirect if no language in URI */
var $default_uri = '';
public function getLanguages()
{
$this->load->model('Lang_model');
return $this->Lang_model->GetLangs();
}
Of course this is just an example of what I'm trying to achieve. It doesn't work and my questions are:
is it a good practise do something like this?
if yes, how can I load my model in that class?
i didn't load most of core classes of CI .
the frequently used class , we load theme in autoload.php file instead of load them every time .
I am trying to edit the PHPWord plugin to better fit my needs. By making the list of sections that the PHPWord main class holds, I can make it so I can insert sections into any order in the document instead of just a fixed list that I can't re-order.
But I am getting an error saying syntax error, unexpected 'new' and it is driving me crazy.
Does anybody else know more about this PHPWord tool? I'm not getting answers from their Github issue tracker/forum.
Something along the lines of they have their defined classes that the tools uses and I need to add it somehow as a resource? I can't just add it in for some reason.
Mucho gracias!
EDIT:
I tried making a new object on this line OTHER than array() or SplDoublyLinkedList() and no matter what other object I try to assign that is outside of the plugin scope I get the 'new' syntax error.
I also tried new ArrayObject(); and I'm still getting the error.
PHPWord uses an Autoloader? This is their autoloader code, do I need to somehow include any extra classes I want to use in here somehow?
namespace PhpOffice\PhpWord;
/**
* Autoloader
*/
class Autoloader
{
/** #const string */
const NAMESPACE_PREFIX = 'PhpOffice\\PhpWord\\';
/**
* Register
*
* #param bool $throw
* #param bool $prepend
* #return void
*/
public static function register($throw = true, $prepend = false)
{
spl_autoload_register(array(new self, 'autoload'), $throw, $prepend);
}
/**
* Autoload
*
* #param string $class
* #return void
*/
public static function autoload($class)
{
$prefixLength = strlen(self::NAMESPACE_PREFIX);
if (0 === strncmp(self::NAMESPACE_PREFIX, $class, $prefixLength)) {
$file = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, $prefixLength));
$file = realpath(__DIR__ . (empty($file) ? '' : DIRECTORY_SEPARATOR) . $file . '.php');
if (file_exists($file)) {
/** #noinspection PhpIncludeInspection Dynamic includes */
require_once $file;
}
}
}
}
You have probably gotten already past this problem, but just to write out the problem answer here in case someone stumbles here and tries to make sense of this case.
As #karthikr mentioned, the problem is using object initialization with new when defining class variable (php: properties):
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
i.e. the correct way to do the initialization is to move the new to the PhpWord class constructor:
private $sections = null;
public function __construct()
{
$sections = new SplDoublyLinkedList();
...
}
I'm trying to create a system that it has a GeneralObj. The GeneralObj allows user to initiate special objects for database's tables with a String of the table name. So far, it works perfect.
class GeneralObj{
function __construct($tableName) {
//...
}
}
However, it is too tired to type new GeneralObj(XXX) every time.
I am wondering is that possible to simplify the process to like new XXX(), which is actually running the same as new GeneralObj(XXX)?
I spot PHP provided __autoload method for dynamic loading files in the setting include_path but it requires a the actually definition file existing. I really don't want to copy and copy the same definition files only changing a little.
For cause, eval is not an option.
Maybe you can just auto-create the files in the autoloader:
function __autoload($class_name) {
// check for classes ending with 'Table'
if (preg_match('/(.*?)Table/', $class_name, $match)) {
$classPath = PATH_TO_TABLES . '/' . $match[1] . '.php';
// auto-create the file
if (!file_exists($classPath)) {
$classContent = "
class $class_name extends GeneralObj {
public __construct() {
parent::__construct('{$match[1]}');
}
}";
file_put_contents($classPath, $classContent);
}
require_once $classPath;
}
}
Use inheritance. Make GeneralObj the superclass of the table specific classes. This way you can dynamically derive class names and instantiate objects. Example:
class someTable extends GeneralObj {
}
$tableName = 'some';
$className = $tableName . 'Table';
$obj = new $className;
No, this is not possible.
The runkit extension allows programmatic manipulation of the PHP runtime environment, but it cannot do this. Even if it could, it would IMHO be a very bad idea, greatly impacting the requirements and complexity of the application in exchange for saving a few keystrokes.
In an unrelated note, your GeneralObj class has functionality that sounds suspiciously like that of a dependency injection container. Perhaps you should consider replacing it with one?
Something like this autoloader:
myAutoloader::Register();
class myAutoloader
{
/**
* Register the Autoloader with SPL
*
*/
public static function Register() {
if (function_exists('__autoload')) {
// Register any existing autoloader function with SPL, so we don't get any clashes
spl_autoload_register('__autoload');
}
// Register ourselves with SPL
return spl_autoload_register(array('myAutoloader', 'Load'));
} // function Register()
/**
* Autoload a class identified by name
*
* #param string $pClassName Name of the object to load
*/
public static function Load($pClassName){
if (class_exists($pClassName,FALSE)) {
// Already loaded
return FALSE;
}
$pClassFilePath = str_replace('_',DIRECTORY_SEPARATOR,$pClassName) . '.php';
if (file_exists($pClassFilePath) === FALSE) {
// Not a class file
return new GeneralObj($pClassName);
}
require($pClassFilePath);
} // function Load()
}
And it's up to GeneralObj to throw an exception if the table class can't be instantiated
Last week I learned that classes can be included in your project by writing an __autoload() function. Then I learned that using an autoloader isn't only a technique but also a pattern.
Now I'm using the autoloader in my project and I've found it very very useful. I was wondering if it could be possible to do the same thing with functions. It could be very useful to forget about including the right PHP file with functions inside it.
So, is it possible to create a function autoloader?
There is no function auto-loader for functions. You have four realistic solutions:
Wrap all functions into namespacing classes (context appropriate). So let's say you have a function called string_get_letters. You could add that to a class called StringFunctions as a static function. So instead of calling string_get_letters(), you'd call StringFunctions::get_letters(). You would then __autoload those namespaced classes.
Pre-load all functions. Since you're using classes, you shouldn't have that many functions, so just pre-load them.
Load functions prior to using them. In each file, require_once the function files that are going to be used in that file.
Don't use functions in the first place. If you are developing OOP code (which it seems like you are anyway), there should be little to no need for functions at all. Everything you would need a function (or multiple) for, you could build in a OO manner and avoid the need for functions.
Personally, I'd suggest either 1, 2 or 4 depending on your exact need and the quality and size of your codebase...
If you are using Composer in your Project, you can add a files directive to the autoload section.
This will than actually generate a require_once in the autoloader, but it feels like real autoloading, because you dont have to take care of that.
Its not lazy loading though.
Example taken from Assetic:
"autoload": {
"psr-0": { "Assetic": "src/" },
"files": [ "src/functions.php" ]
}
I read something a while back about an ugly hack that caught fatal errors and tried to include and execute the missing function(s), but I definitely wouldn't go that road.
The closest thing you have is the __call() magic method, which is sort of a __autoload() for methods, not functions. It might be good enough for your needs; if you can afford to call a class and require each different function separately. Since PHP 5.3.0, you also have __callStatic().
An example using __callStatic():
class Test
{
public function __callStatic($m, $args)
{
if (function_exists($m) !== true)
{
if (is_file('./path/to/functions/' . $m . '.php') !== true)
{
return false;
}
require('./path/to/functions/' . $m . '.php');
}
return call_user_func_array($m, $args);
}
}
Test::functionToLoad(1, 2, 3);
This would call the functionToLoad() function defined in ./path/to/functions/functionToLoad.php.
Well, as usual there is a PECL extension for that:
automapPECL
(via: http://phk.tekwire.net/joomla/support/doc/automap.htm)
It's supposed to autoload functions as well as classes. Which however doesn't work with the current PHP interpreter yet.
(An alternative option btw, is generating stub functions that load and run namespaced counterparts.)
That being said. Autoloading is not universally considered a good practice. It leads to overly fractured class hierarchies and object happiness. And the real reason PHP has autoloading is because include and dependency management systems are inmature.
namespace MyNamespace;
class Fn {
private function __construct() {}
private function __wakeup() {}
private function __clone() {}
public static function __callStatic($fn, $args) {
if (!function_exists($fn)) {
$fn = "YOUR_FUNCTIONS_NAMESPACE\\$fn";
require str_replace('\\', '/', $fn) . '.php';
}
return call_user_func_array($fn, $args);
}
}
And using namespaces, we can do: Fn::myFunc() and spl_autoload_register(). I've used this code with examples at: https://goo.gl/8dMIMj
I use a Class and __invoke. The __invoke method is called when a script calls a class as a function. I often do something like this:
<?php
namespace API\Config;
class Slim {
function __invoke() {
return [
'settings' => [
'displayErrorDetails' => true,
'logger' => [
'name' => 'api',
'level' => Monolog\Logger\Logger::DEBUG,
'path' => __DIR__ . '/../../logs/api.log',
],
]
];
}
}
I can then call like a function:
$config = API\Config\Slim;
$app = Slim\App($config())
new Functions\Debug() will load functions to root namespace.
namespace Functions
{
class Debug
{
}
}
namespace
{
if (! function_exists('printr')) {
/**
*
* #param mixed $expression
*/
function printr()
{
foreach (func_get_args() as $v) {
if (is_scalar($v)) {
echo $v . "\n";
} else {
print_r($v);
}
}
exit();
}
}
}
Here is another rather complex example, based on the suggestions in this discussion.
The code can also be seen here: lib/btr.php
<?php
/**
* A class that is used to autoload library functions.
*
* If the function btr::some_function_name() is called, this class
* will convert it into a call to the function
* 'BTranslator\some_function_name()'. If such a function is not
* declared then it will try to load these files (in this order):
* - fn/some_function_name.php
* - fn/some_function.php
* - fn/some.php
* - fn/some/function_name.php
* - fn/some/function.php
* - fn/some/function/name.php
* The first file that is found will be loaded (with require_once()).
*
* For the big functions it makes more sense to declare each one of them in a
* separate file, and for the small functions it makes more sense to declare
* several of them in the same file (which is named as the common prefix of
* these files). If there is a big number of functions, it can be more
* suitable to organize them in subdirectories.
*
* See: http://stackoverflow.com/questions/4737199/autoloader-for-functions
*/
class btr {
/**
* Make it TRUE to output debug info on '/tmp/btr.log'.
*/
const DEBUG = FALSE;
/**
* The namespace of the functions.
*/
const NS = 'BTranslator';
/**
* Relative directory where the functions are located.
*/
const FN = 'fn';
private function __construct() {}
private function __wakeup() {}
private function __clone() {}
/**
* Return the full name (with namespace) of the function to be called.
*/
protected static function function_name($function) {
return self::NS . '\\' . $function;
}
/**
* Return the full path of the file to be loaded (with require_once).
*/
protected static function file($fname) {
return dirname(__FILE__) . '/' . self::FN . '/' . $fname . '.php';
}
/**
* If a function does not exist, try to load it from the proper file.
*/
public static function __callStatic($function, $args) {
$btr_function = self::function_name($function);
if (!function_exists($btr_function)) {
// Try to load the file that contains the function.
if (!self::load_search_dirs($function) or !function_exists($btr_function)) {
$dir = dirname(self::file($fname));
$dir = str_replace(DRUPAL_ROOT, '', $dir);
throw new Exception("Function $btr_function could not be found on $dir");
}
}
return call_user_func_array($btr_function, $args);
}
/**
* Try to load files from subdirectories
* (by replacing '_' with '/' in the function name).
*/
protected static function load_search_dirs($fname) {
do {
self::debug($fname);
if (file_exists(self::file($fname))) {
require_once(self::file($fname));
return TRUE;
}
if (self::load_search_files($fname)) {
return TRUE;
}
$fname1 = $fname;
$fname = preg_replace('#_#', '/', $fname, 1);
} while ($fname != $fname1);
return FALSE;
}
/**
* Try to load files from different file names
* (by removing the part after the last undescore in the functin name).
*/
protected static function load_search_files($fname) {
$fname1 = $fname;
$fname = preg_replace('/_[^_]*$/', '', $fname);
while ($fname != $fname1) {
self::debug($fname);
if (file_exists(self::file($fname))) {
require_once(self::file($fname));
return TRUE;
}
$fname1 = $fname;
$fname = preg_replace('/_[^_]*$/', '', $fname);
}
return FALSE;
}
/**
* Debug the order in which the files are tried to be loaded.
*/
public static function debug($fname) {
if (!self::DEBUG) {
return;
}
$file = self::file($fname);
$file = str_replace(DRUPAL_ROOT, '', $file);
self::log($file, 'Autoload');
}
/**
* Output the given parameter to a log file (useful for debugging).
*/
public static function log($var, $comment ='') {
$file = '/tmp/btr.log';
$content = "\n==> $comment: " . print_r($var, true);
file_put_contents($file, $content, FILE_APPEND);
}
}
While you can't autoload functions and constants, you can use something like jesseschalken/autoload-generator which will automatically detect what files contain things which can't be autoloaded and load them eagerly.
The solution I came up with. As lightweight as I could come up with.
class functions {
public static function __callstatic($function, $arguments) {
if (!function_exists($function)) {
$file = strtok($function, '_') .'.php';
include '/path/to/functions/'.$file;
}
return call_user_func_array($function, $arguments);
}
}
Use it by calling functions::foo_bar($anything).
I try to use the autoloading of classes to my advantage. So, when a class is auto-loaded, the class file is executed. Therefore, I create a class with a static method called 'boot' that does nothing. When I invoke that method, the class will be autoloaded, hence every function in that file will be defined in the global scope. What's even more interesting is that the functions will be defined in the namespace of the class, so there are no clashes.
For example:
<?PHP
namespace Functions;
// functions are defined in this file
class GlobalFunctions{
public static function boot(){};
}
function foo(){ // code... }
?>
// the client file
<?php
// VS Code automatically does this.
use Functions\GlobalFunctions;
use function Functions\foo;
// I usually put this in the bootstrap file
GlobalFunctions::boot();
// call foo() from the Functions namespace
foo();
?>
Include all functions file in one file and then include it
//File 1
db_fct.php
//File 2
util_fct.php
//In a functions.php include all other files
<?php
require_once 'db_fct.php';
require_once 'util_fct.php';
?>
Include functions.php whenever you need functions ..
try this
if ($handle = opendir('functions')) {
while (false !== ($entry = readdir($handle))) {
if (strpos($entry, '.php') !== false) {
include("functions/$entry");
}
}
closedir($handle);
}
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.