Skip to content

Instantly share code, notes, and snippets.

@socketz
Last active August 29, 2015 14:05
Show Gist options
  • Save socketz/75852636289b07114302 to your computer and use it in GitHub Desktop.
Save socketz/75852636289b07114302 to your computer and use it in GitHub Desktop.
Factory Pattern: Example of class inheritance, using a Factory constructor for components
/*
This is a snippet of code, using a Factory class constructor with modules of apps,
it's a simple but effective architecture, the differents apps can use other patterns internally
*/
<?php
class AppComponent {
private $myVar;
public function __construct(){
//Initialize with our variables
$this->myVar = "";
}
public function run(){
$route = !empty($_GET['route']) ? $_GET['route'] : $this->getFirstComponentActive();
switch($route){
case 'web':
ComponentFactory::getComponent("WebController")->run();
break;
}
}
}
class ComponentFactory {
private static function includeClass($className){
if(!class_exists($className, false)){
if(file_exists($className.".php")){
require_once(trim($className).".php");
}
}
}
public static function getClass($className){
ComponentFactory::includeClass($className);
return new $className();
}
}
//Call the class to load, for example, a class from a module
ComponentFactory::getComponent("AppComponent")->run();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment