Answer the question
In order to leave comments, you need to log in
How to make a callback function in php like in Laravel?
Hello, I want to create an MVC app, I take an example from Laravel, there is a function
Route::get('/', function () {
return view('welcome');
});
//или
Route::get('/', '[email protected]');
//index.php
require "Debug.php";
use app\core\Router;
spl_autoload_register(function($class){
$path = str_replace('\\','/',$class).'.php';
if(file_exists($path)){
require $path;
}
});
session_start();
require 'app/core/web.php';
$router = new Router;
//Router.php
namespace app\core;
class Router{
public static $routes = [];
public function __construct(){
$uri = $_SERVER['REQUEST_URI'];
if(array_search($uri,self::$routes)){
echo $uri;
}else{
header('Location:/beejee/404');
}
}
static public function get($url,$param){
echo $param;
self::$routes[] = '/beejee'.$url;
}
static public function post($url){
self::$routes[] = '/beejee'.$url;
}
static public function put($url){
self::$routes[] = '/beejee'.$url;
}
static public function delete($url){
self::$routes[] = '/beejee'.$url;
}
}
//web.php
use app\core\Router;
Router::get('/',function(){
return 'home';
});
Router::get('/admin',function(){
return 'asd';
});
Router::get('404');
Answer the question
In order to leave comments, you need to log in
public function __construct(){
$uri_path = $_SERVER['REQUEST_URI']; // Тут нужно как-то получить PATH часть из ссылки, можно через parse_url
if(isset(self::$routes[$uri_path]) && is_callable(self::$routes[$uri_path])){
return call_user_func( self::$routes[$uri_path] ); // Вызов callback функции
}else{
header('Location:/beejee/404');
}
}
static public function get( $url, $callback ){
self::$routes[$url] = $callback;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question