bramus / router

A lightweight and simple object oriented PHP Router

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to do the following

ErikThiart opened this issue · comments

$router->get('/', 'index.php');
$router->get('/about', 'about.php');
$router->get('/contact', 'contact.php');

$router->get('/notes', 'notes/index.php')->only('auth');
$router->get('/note', 'notes/show.php');
$router->delete('/note', 'notes/destroy.php');

CleanShot 2023-10-05 at 11  54 03

I know the routers and screenshot do not match, ignore that. Conceptionally I want to understand how I can send the route to a specific PHP file in the controller.

example

$router->get('/user', 'User/index.php');

This is how I currently do it, but it feels... dirty.

// Define routes
$router->get('/', include_once '../App/Controllers/User/index.php');

Hi Erik,
a router normally just calls Controller functions / classes that are inside a file, not a file itself. That's what MVC (Model View Controller) is.

  • Model -> Database
  • View -> Template Engine like Mustache, Twig etc
  • Controller -> App Logic

👉🏻 https://www.freecodecamp.org/news/the-model-view-controller-pattern-mvc-architecture-and-frameworks-explained/

to import the file there are two ways:

  1. when the app is tiny, you can for learning purposes include all your controller files in the router function, but I will take a lot of performance, since php will read them all in with dependencies
  2. you take a look into autoload. Composer also uses autoload already, and you can just include it. Autoload means PHP knows itself when to include which file when and only if needed and called (preferred solution)

Youtube How to autoload:
https://www.youtube.com/results?search_query=autoload+composer

Maybe this helps to see, besides passing the function by name / reference you can also define an anonymous function in it itself (shown here, but rather quick and dirty)
https://github.com/bramus/router/blob/master/demo/index.php