A solution for a PHP website without a framework
- by lortabac
One of our customers asked us to add some dynamic functionality to an existent website, made of several static HTML pages.
We normally work with an MVC framework (mostly CodeIgniter), but in this case moving everything to a framework would require too much time.
Since it is not a big project, not having the full functionality of a framework is not a problem. But the question is how to keep code clean.
The solution I came up with is to divide code in libraries (the application's API) and models. So inside HTML there will only be API calls, and readability will not be sacrificed.
I implemented this with a sort of static Registry (sorry if I'm wrong, I am not a design pattern expert):
<?php
class Custom_framework {
//Global database instance
private static $db;
//Registered models
private static $models = array();
//Registered libraries
private static $libraries = array();
//Returns a database class instance
static public function get_db(){
if(isset(self::$db)){
//If instance exists, returns it
return self::$db;
} else {
//If instance doesn't exists, creates it
self::$db = new DB;
return self::$db;
}
}
//Returns a model instance
static public function get_model($model_name){
if(isset(self::$models[$model_name])){
//If instance exists, returns it
return self::$models[$model_name];
} else {
//If instance doesn't exists, creates it
if(is_file(ROOT_DIR . 'application/models/' . $model_name . '.php')){
include_once ROOT_DIR . 'application/models/' . $model_name . '.php';
self::$models[$model_name] = new $model_name;
return self::$models[$model_name];
} else {
return FALSE;
}
}
}
//Returns a library instance
static public function get_library($library_name){
if(isset(self::$libraries[$library_name])){
//If instance exists, returns it
return self::$libraries[$library_name];
} else {
//If instance doesn't exists, creates it
if(is_file(ROOT_DIR . 'application/libraries/' . $library_name . '.php')){
include_once ROOT_DIR . 'application/libraries/' . $library_name . '.php';
self::$libraries[$library_name] = new $library_name;
return self::$libraries[$library_name];
} else {
return FALSE;
}
}
}
}
Inside HTML, API methods are accessed like this:
<?php echo Custom_framework::get_library('My_library')->my_method(); ?>
It looks to me as a practical solution. But I wonder what its drawbacks are, and what the possible alternatives.