Я сожалею о количестве кода здесь. Я пытался показать достаточно для понимания, избегая путаницы (я надеюсь). Я включил вторую копию кода на Pastebin . (Код выполняется без ошибок / уведомлений / предупреждений.)
В настоящее время я создаю систему управления контентом, пытаясь реализовать идею Model View Controller. Я только недавно натолкнулся на концепцию MVC (в течение последней недели) и пытаюсь реализовать ее в моем текущем проекте.
Одной из функций CMS являются динамические / настраиваемые области меню, и каждая функция будет представлена контроллером. Поэтому будет несколько версий класса Controller, каждая с определенной расширенной функциональностью.
Я просмотрел несколько руководств и прочитал некоторые решения с открытым исходным кодом для MVC Framework. Сейчас я пытаюсь создать облегченное решение для моих конкретных требований. Меня не интересует обратная совместимость, я использую PHP 5.3. Преимущество базового класса заключается в том, что нет необходимости использовать global
, и он может напрямую обращаться к любому загруженному классу, используя $this->Obj['ClassName']->property/function();
.
Надеемся получить некоторую обратную связь, используя основную структуру (с учетом производительности). В частности,
а) Правильно ли я понял / реализовал концепцию MVC?
б) Правильно ли я понял / реализовал объектно-ориентированные методы в PHP 5?
в) Должны ли свойства класса Base быть статическими?
г) улучшения?
Заранее большое спасибо!
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
/* A "Super Class" that creates instances */
class Base {
public static $Obj = array(); // Not sure this is the correct use of the "static" keyword?
public static $var;
static public function load_class($directory, $class)
{
echo count(self::$Obj)."\n"; // This does show the array is getting updated and not creating a new array :)
if (!in_array($class, self::$Obj)) //dont want to load it twice
{
/* Locate and include the class file based upon name ($class) */
return self::$Obj[$class] = new $class();
}
return TRUE;
}
}
/* Loads general configuration objects into the "Super Class" */
class Libraries extends Base {
public function __construct(){
$this->load_class('library', 'Database');
$this->load_class('library', 'Session');
self::$var = 'Hello World!'; //testing visibility
/* Other general funciton classes */
}
}
class Database extends Base {
/* Connects to the the database and executes all queries */
public function query(){}
}
class Session extends Base {
/* Implements Sessions in database (read/write) */
}
/* General functionality of controllers */
abstract class Controller extends Base {
protected function load_model($class, $method) {
/* Locate and include the model file */
$this->load_class('model', $class);
call_user_func(array(self::$Obj[$class], $method));
}
protected function load_view($name) {
/* Locate and include the view file */
#include('views/'.$name.'.php');
}
}
abstract class View extends Base { /* ... */ }
abstract class Model extends Base { /* ... */ }
class News extends Controller {
public function index() {
/* Displays the 5 most recent News articles and displays with Content Area */
$this->load_model('NewsModel', 'index');
$this->load_view('news', 'index');
echo self::$var;
}
public function menu() {
/* Displays the News Title of the 5 most recent News articles and displays within the Menu Area */
$this->load_model('news/index');
$this->load_view('news/index');
}
}
class ChatBox extends Controller { /* ... */ }
/* Lots of different features extending the controller/view/model class depending upon request and layout */
class NewsModel extends Model {
public function index() {
echo self::$var;
self::$Obj['Database']->query(/*SELECT 5 most recent news articles*/);
}
public function menu() { /* ... */ }
}
$Libraries = new Libraries;
$controller = 'News'; // Would be determined from Query String
$method = 'index'; // Would be determined from Query String
$Content = $Libraries->load_class('controller', $controller); //create the controller for the specific page
if (in_array($method, get_class_methods($Content)))
{
call_user_func(array($Content, $method));
}
else
{
die('Bad Request'. $method);
}
$Content::$var = 'Goodbye World';
echo $Libraries::$var . ' - ' . $Content::$var;
?>
/* Output */
0
1
2
3
Hello World!Hello World!Goodbye World - Goodbye World