Viktor86
Новичок
Здравствуйте. Относительно недавно начал изучать PHP. Вот дошло дело до единой точки входа. Написал (кое-что скопировал
) FrontController. Работает!
Подскажите, пожалуйста, правильно ли все написал, если нет, скажите как лучше сделать:
PS:
Не пишу фреймворк, не пишу сайт - написал для практики!!!
Заранее спасибо
![Smile :) :)](/talk/styles/default/xenforo/smilies/smile.png)
Подскажите, пожалуйста, правильно ли все написал, если нет, скажите как лучше сделать:
PHP:
namespace main;
class Application {
private $controller = "index";
private $action = "index";
private $model;
private $params = array();
public function __construct($config) {
$path = $this->getUri();
$request = explode("/", $path, 3);
// Выбор контроллера
if (!empty($request[0])) {
$this->controller = $request[0];
}
// Выбор действия
if (!empty($request[1])) {
$this->action = $request[1];
}
// Выбор параметров
if (!empty($request[2])) {
$this->setParams($request[2]);
}
// Добавление префиксов
$this->controller = ucfirst($this->controller) . 'Controller';
$this->model = ucfirst($this->controller) . 'Model';
$this->action = 'action' . ucfirst($this->action);
$basePath = $config['basePath'];
$dir = DIRECTORY_SEPARATOR;
// Абсолютный путь к классу
$controllerPath = $basePath . $dir . 'controllers' . $dir . $this->controller . '.php';
$modelPath = $basePath . $dir . 'models' . $dir . $this->controller . '.php';
// Подключаем контроллер
if (file_exists($controllerPath)) {
require_once $controllerPath;
// Подключаем модель
if (file_exists($modelPath)) {
require_once $modelPath;
}
$cont = "app\controllers\\".$this->controller;
$controller = new $cont;
$action = $this->action;
if (method_exists($controller, $action)) {
$controller->$action($this->params);
} else {
// ИСКЛЮЧЕНИЕ
die($this->action . " не существует!");
}
} else {
// ИСКЛЮЧЕНИЕ
die($this->controller . " не существует!");
}
}
private function getUri() {
$uri = trim($_SERVER["REQUEST_URI"],"/");
return preg_replace('/[^a-zA-Z0-9]\//', "", $uri);
}
private function setParams($param) {
$split = explode('/', $param);
$key = array();
$value = array();
for($i=0;$i<count($split);$i++) {
if($i % 2 == 0) {
$key[] = $split[$i];
} else {
$value[] = $split[$i];
}
}
$this->params = array_combine($key, $value);
}
}
Не пишу фреймворк, не пишу сайт - написал для практики!!!
Заранее спасибо