merhaba bu tarz basit islermler icin kendi kullandigim boyle bir yapi var. Baska bir makaleden alıntıdır. Ama çok eski olduğu için kaynağını bulamadım
index.php
define("ROOT", __DIR__.DIRECTORY_SEPARATOR);
define("VIEW", ROOT."View".DIRECTORY_SEPARATOR);
define("CONTROLLER", ROOT."Controller".DIRECTORY_SEPARATOR);
define("CORE", ROOT."Core".DIRECTORY_SEPARATOR);
require_once(CORE . "Application.php");
new Application();
burda sabit leri tanımlıyorsun. klasor yapisi asagidaki gibi
/
|
/app
| - core
| - view
| - controller
index.php
burada urlden gerekli controller ve actioni cagiriyor
core/application.php
class Application {
protected $controller = "HomeController";
protected $action = "IndexAction";
protected $parameters = array();
public function __construct(){
$this->ParseURL();
if(file_exists(CONTROLLER.$this->controller.".php")){
require_once (CONTROLLER.$this->controller.".php");
$this->controller = new $this->controller;
if(method_exists($this->controller, $this->action)){
call_user_func_array([$this->controller, $this->action], $this->parameters);
} else {
echo "Böyle Bir Action Yok.";
}
} else {
echo "Böyle Bir Controller Yok.";
}
}
protected function ParseURL(){
$request = trim($_SERVER["REQUEST_URI"], "/");
if (!empty($request)){
$url = explode("/", $request);
$this->controller = isset($url[0]) ? $url[0]."Controller" : "HomeController";
$this->action = isset($url[1]) ? $url[1]."Action" : "IndexAction";
unset($url[0], $url[1]);
$this->parameters = !empty($url) ? array_values($url) : array();
} else {
$this->controller = "HomeController";
$this->action = "IndexAction";
$this->parameters = array();
}
}
}
core/controller.php
require_once(CORE . "View.php");
class Controller {
protected $view;
public function View($view_name, $model = []){
$this->view = new View($view_name, $model);
return $this->view->Render();
}
public function Redirect($path)
{
header("Location: {$path}");
}
}
core/view.php
class View {
protected $view_file;
protected $view_model;
public function __construct($view_file, $view_model){
$this->view_file = $view_file;
$this->view_model = $view_model;
}
public function Render(){
if(file_exists(VIEW.$this->view_file.".php")){
extract($this->view_model);
ob_start();
ob_get_clean();
include_once (VIEW.$this->view_file.".php");
}
}
}
mesela anasayfa icin
controllers/HomeController.php
require_once(CORE . "Controller.php");
class HomeController extends Controller {
public function IndexAction(){
// view/Home/Index.php
$this->View("/Home/Index");
}
// sehirler icin
// urlnin /sehir/istanbul oldugunu varsayalim
public function sehirAction() {
$this->parameters[0] // istanbul
}
}
edit: htaccess ile url rewrite edip butun istekleri index.php ye yonlendirmeniz gerekiyor
edit: soyle bir ornek hazirladim
browserdan /sehirler/sehir/istanbul veya /sehirler/sehir/ankara gidersen sayfanin dinamik olarak render oldugunu gorebilmen lazim
https://github.com/KerimCETINBAS/phpMvcSehir